package com.zxdemo.utils

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 com.zxdemo.http.ZxHttp
import org.json.JSONObject


class FcmUtils {

    fun initFirebase(context: Context?) {
        FirebaseApp.initializeApp(context!!)
        getToken()
    }

    fun subscribeToTopic(topic: String) {
        Log.d("TAG", "subscribeToTopic: $topic")
        FirebaseMessaging.getInstance().subscribeToTopic(topic).addOnCompleteListener {
            Log.d("TAG", "subscribeToTopic:isSuccessful ${it.isSuccessful}")
            if (it.isSuccessful) {
                getToken()
                ZxHttp.getHttpReportInterface("FCM_Topic$topic", "", null)
                Log.d("FCMUtil", "suc")
            } else {
                Log.d("FCMUtil", "fail")
            }
        }
    }

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

    /**
     * 有vpn有google商店才能获取
     */
    private fun getToken() {
        FirebaseMessaging.getInstance().token
            .addOnCompleteListener(object : OnCompleteListener<String> {
                override fun onComplete(task: Task<String>) {
                    if (!task.isSuccessful) {
                        Log.e("FCM", "Fetching FCM registration token failed", task.exception)
                        return
                    }
                    // Get new FCM registration token
                    val token: String = task.result
                    val json = JSONObject()
                    json.put("token", token)
                    Log.e("getToken", "token=$token")
                    ZxHttp.getHttpReportInterface("fcm_message_received", "", json)

                    SpUtils.getInstance().putString("token", token)
                }
            })
    }
}