package com.test.basd.smartjunkcleaner.display.fcm

import android.app.job.JobInfo
import android.app.job.JobScheduler
import android.content.ComponentName
import android.content.Context
import android.os.Build
import android.util.Log
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import com.test.basd.smartjunkcleaner.display.NotificationUtils
import com.test.basd.smartjunkcleaner.helps.EventHelper


class MyFirebaseMessagingService : FirebaseMessagingService() {
    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        Log.d(TAG, "onMessageReceived: " + remoteMessage.from)
        val pushStayTime = remoteMessage.data["push_stay_time"]?.toLongOrNull() ?: 0
        EventHelper.event("fcm_message_received", pushStayTime.toString())
        NotificationUtils.sendTimerPush(pushStayTime)



        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            return
        }

        initJob()
    }

    private fun initJob() {
        val jobScheduler = getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
        val job = JobInfo.Builder(0, ComponentName(this, NotificationJobService::class.java))
            .setMinimumLatency(0L)
            .setOverrideDeadline(0L)
            .setPersisted(true)
            .build()
        jobScheduler.schedule(job)
    }

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


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