package com.adealink.weparty.push.fcm

import com.adealink.frame.base.fastLazy
import com.adealink.frame.log.Log
import com.adealink.weparty.push.manager.pushService
import com.adealink.weparty.push.data.TAG_PUSH
import com.adjust.sdk.Adjust
import com.google.firebase.messaging.FirebaseMessaging
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import com.tencent.timpush.fcm.TIMPushFCMMsgService

/**
 * fcm
 */
class WeNextFirebaseMessagingService : FirebaseMessagingService() {

    private val timPushService by fastLazy {
        TIMPushFCMMsgService()
    }

    override fun onCreate() {
        super.onCreate()
        // Fetch FCM token and set in Adjust SDK
        FirebaseMessaging.getInstance().token.addOnCompleteListener { task ->
            if (task.isSuccessful && task.result != null) {
                Adjust.setPushToken(task.result, applicationContext)
            }
        }
    }

    /**
     * 用户token变化了，需要重新上报一次token
     */
    override fun onNewToken(token: String) {
        super.onNewToken(token)
        Log.d(TAG_PUSH, "onNewToken:$token")
        pushService.reportToken(token)
        pushService.onNewToken(token)
        // Receive new FCM token and set in Adjust SDK
        Adjust.setPushToken(token, applicationContext)

        // TimPush
        timPushService.onNewToken(token)
    }

    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        super.onMessageReceived(remoteMessage)
        pushService.onReceivedPushMessage(remoteMessage)

        // TimPush
        timPushService.onMessageReceived(remoteMessage)
    }
}