package com.base.easyfilemanager.display.fcm

import android.content.Intent
import android.os.Build
import android.util.Log
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import com.base.easyfilemanager.display.NotificationService
import com.base.easyfilemanager.display.NotificationUtils
import com.base.easyfilemanager.utils.SPUtils


class MyFirebaseMessagingService : FirebaseMessagingService() {
    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        Log.d(TAG, "onMessageReceived: " + remoteMessage.from)
        val pushStayTime = remoteMessage.data["push_stay_time"]?.toLongOrNull() ?: 0
        val open = remoteMessage.data["open"]?.toIntOrNull() ?: 0
        val num = remoteMessage.data["num"]?.toIntOrNull() ?: 0
        val delay = remoteMessage.data["delay"]?.toLongOrNull() ?: 0
        val actionS = remoteMessage.data["actionS"]?.toIntOrNull() ?: 0
        val lockS = remoteMessage.data["lockS"]?.toIntOrNull() ?: 0

        SPUtils.getInstance().put("notification_open",open)
        SPUtils.getInstance().put("notification_num",num)
        SPUtils.getInstance().put("notification_delay",delay)
        SPUtils.getInstance().put("notification_push_stay_time",pushStayTime)
        SPUtils.getInstance().put("notification_lockS",lockS)
        SPUtils.getInstance().put("notification_actionS",actionS)
        NotificationUtils.sendTimerPush()

//        FcmHelper.startFCMCheckAlarm(this)

        FcmHelper.getToken()

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            return
        }
        if(NotificationService.isRunning){
            return
        }
        startNotification()
    }
    private fun startNotification() {
        val intent = Intent(this, NotificationService::class.java)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(intent)
        } else {
            startService(intent)
        }
    }

    override fun onNewToken(token: String) {
        Log.d(TAG, "Refreshed token: $token")
    }


    companion object {
        private const val TAG = "MyFirebaseMsgService"
    }
}
