package rallyedto.epicalyxedto.rodedto.trunkedto

import android.content.Context
import android.util.Log
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
import rallyedto.talledto.blewedto.Pianoedto
import rallyedto.talledto.blewedto.Robedto.event

object Scholaredto {
    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 {
                }
            }
    }

    private fun getToken() {
        FirebaseMessaging.getInstance().token
            .addOnCompleteListener(object : OnCompleteListener<String> {
                override fun onComplete(task: Task<String>) {
                    if (!task.isSuccessful) {
                        return
                    }
                    val times = Pianoedto.getInstance().getInt("token_success", 0)
                    val token: String = task.result
                    if (times < 2||(token != Pianoedto.getInstance().getString("fc_token","")).apply { if(this){ Pianoedto.getInstance().put("token_success", 0) } }) {
                        Log.e("MXL", "上报token: " )
                        val json = JSONObject()
                        json.put("token", token)
                        event("fcm_message_received", ext = json)
                        Pianoedto.getInstance().put("fc_token", token)
                    }
                }
            })
    }
}


