package com.swiftcleaner.chovey.business.push

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

object FirebaseUtils {

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

    fun subscribeToTopic(topic: String, complete: (() -> Unit?)? = null) {
        FirebaseMessaging.getInstance().subscribeToTopic(topic)
            .addOnCompleteListener { task ->
                if (task.isSuccessful) {
                    complete?.invoke()
                } else {

                }
            }
    }

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

                } else {

                }
            }
    }

    fun getToken(complete: ((String) -> Unit?)? = null) {
        FirebaseMessaging.getInstance().token
            .addOnCompleteListener(object : OnCompleteListener<String> {
                override fun onComplete(task: Task<String>) {
                    if (!task.isSuccessful) {
                        Log.d("FCM", "Fetching FCM registration token failed", task.exception)
                        return
                    }
                    // Get new FCM registration token
                    val token: String = task.result
                    complete?.invoke(token)
                    // Handle new token
                    Log.d("FCM", "FCM Registration Token: $token")
                }
            })
    }
}