package com.base.filerecoveryrecyclebin.fcm

import android.content.Context
import android.util.Log
import com.base.filerecoveryrecyclebin.utils.AppPreferences
import com.base.filerecoveryrecyclebin.utils.EventUtils.event
import com.base.filerecoveryrecyclebin.utils.LogEx
import com.google.android.gms.tasks.OnCompleteListener
import com.google.android.gms.tasks.Task
import com.google.firebase.FirebaseApp
import com.google.firebase.messaging.FirebaseMessaging
import org.json.JSONObject

object FCMManager {
    // 用于保存FCM token
    private var token: String? = null
    fun initFirebase(context: Context?) {
        FirebaseApp.initializeApp(context!!)
        getToken()
    }

    fun subscribeToTopic(topic: String) {
        FirebaseMessaging.getInstance().subscribeToTopic(topic)
            .addOnCompleteListener { task ->
                if (task.isSuccessful) {
                    getToken()
                    Log.d("FCMUtil", "suc:$topic")
                    event("FCM_Topic_$topic", null, null, false)
                } else {
                    Log.d("FCMUtil", "fail")
                }
            }
    }

    fun unsubscribeFromTopic(topic: String?) {
        FirebaseMessaging.getInstance().unsubscribeFromTopic(topic!!)
            .addOnCompleteListener { task ->
                if (task.isSuccessful) {
                } else {
                }
            }
    }

    fun getToken() {
        FirebaseMessaging.getInstance().token
            .addOnCompleteListener(object : OnCompleteListener<String> {
                override fun onComplete(task: Task<String>) {
                    LogEx.logDebug("FCM", "onComplete ${task.isSuccessful}")
                    if (!task.isSuccessful) {
                        Log.e("FCM", "Fetching FCM registration token failed", task.exception)
                        return
                    }
                    // Get new FCM registration token
                    token = task.result
                    LogEx.logDebug("FCM", "token=$token")
                    val json = JSONObject()
                    json.put("token", token)

                    event("fcm_message_received", ext = json)

                    AppPreferences.getInstance().put("token", token)

                    // Handle new token
                    Log.d("FCM", "FCM Registration Token: $token")

                }
            })
    }
    fun getTokenValue(): String? {
        return token
    }
}


