package com.adealink.weparty.push.manager

import com.adealink.frame.frame.BaseFrame
import com.adealink.frame.frame.IListener
import com.adealink.frame.log.Log
import com.adealink.weparty.module.account.AccountModule
import com.adealink.weparty.push.data.TAG_PUSH
import com.adealink.weparty.push.listener.IGetTokenListener
import com.google.android.gms.tasks.OnCompleteListener
import com.google.firebase.messaging.FirebaseMessaging
import com.google.firebase.messaging.RemoteMessage
import kotlinx.coroutines.launch

val pushService: IPushService by lazy { PushService() }

class PushService: BaseFrame<IListener>(), IPushService {

    override fun onNewToken(token: String) {
        //上报新Token
    }

    override fun getToken(listener: IGetTokenListener) {
        FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task ->
            if (!task.isSuccessful) {
                Log.w(TAG_PUSH, "Fetching FCM registration token failed", task.exception)
                listener.onFailed()
                return@OnCompleteListener
            }
            val token = task.result
            val msg = "PushManager, getToken: $token"
            Log.d(TAG_PUSH, msg)
            listener.onSuccess(token)
        })
    }

    override fun getPushTokenAndReport() {
        getToken(object : IGetTokenListener {
            override fun onSuccess(token: String?) {
                if (token.isNullOrEmpty()) {
                    return
                }
                // TODO: 上报新Token
            }

            override fun onFailed() {
            }
        })
    }

    override fun reportToken(token: String) {
        if (!AccountModule.isLogin()) {
            return
        }
        launch {

        }
    }

    override fun onReceivedPushMessage(remoteMessage: RemoteMessage) {

    }
}