package com.aiosman.riderpro

import android.content.Context
import android.util.Log
import cn.jpush.android.api.JPushInterface
import com.aiosman.riderpro.data.AccountService
import com.aiosman.riderpro.data.AccountServiceImpl
import com.google.android.gms.tasks.OnCompleteListener
import com.google.firebase.messaging.FirebaseMessaging
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

object Messaging {
    fun registerDevice(scope: CoroutineScope, context: Context) {

        registerJpush(scope, context)
//        registerFCM(scope)
    }

    suspend fun unregisterDevice(context: Context) {
        unregisterJpush(context)
    }


    fun registerJpush(scope: CoroutineScope, context: Context) {
        val accountService: AccountService = AccountServiceImpl()
        val regId = JPushManager.getRegistrationID(context)
        scope.launch {
            accountService.registerMessageChannel(client = "jpush", identifier = regId)
        }
    }

    private suspend fun unregisterJpush(context: Context) {
        val accountService: AccountService = AccountServiceImpl()
        val regId = JPushManager.getRegistrationID(context)
        accountService.unregisterMessageChannel(client = "jpush", identifier = regId)
    }

    fun registerFCM(scope: CoroutineScope) {
        val accountService: AccountService = AccountServiceImpl()
        FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task ->
            if (!task.isSuccessful) {
                Log.w("Pushing", "Fetching FCM registration token failed", task.exception)
                return@OnCompleteListener
            }

            // Get new FCM registration token
            val token = task.result

            // Log and toast
            Log.d("Pushing", token)
            scope.launch {
                accountService.registerMessageChannel(client = "fcm", token)
            }
        })
    }

}