package com.dumpster.cleaner.business.push.fcm

import android.content.Context
import android.util.Log
import com.dumpster.cleaner.SpConstObject.fcmToken
import com.dumpster.cleaner.business.helper.EventUtils.event
import com.dumpster.cleaner.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 {

    fun initFirebase(context: Context?) {
        FirebaseApp.initializeApp(context!!)
        LogEx.logDebug("initFirebase", "initFirebase")
        getToken()
    }

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

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

    /**
     * 有vpn有google商店才能获取
     */
    private 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
                    val token: String = task.result
                    LogEx.logDebug("FCM", "token=$token")
                    val json = JSONObject()
                    json.put("token", token)
                    event("fcm_message_received", ext = json)

                    fcmToken = token

                    // Handle new token
                    LogEx.logDebug("FCM", "FCM Registration Token: $token")
                }
            })
    }
}


