package com.seven.ikar.kotlin.core.push

import android.util.Log
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import com.seven.ikar.kotlin.app.IkarNativeApp
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class IkarFirebaseMessagingService : FirebaseMessagingService() {
    override fun onNewToken(token: String) {
        super.onNewToken(token)
        val app = applicationContext as? IkarNativeApp ?: return
        CoroutineScope(Dispatchers.IO).launch {
            runCatching {
                app.container.pushRegistrationManager.onTokenRefreshedAsync(token)
            }.onFailure { error ->
                Log.e(LOG_TAG, "OnNewToken failed", error)
            }
        }
    }

    override fun onMessageReceived(message: RemoteMessage) {
        super.onMessageReceived(message)
        runCatching {
            val data = message.data.orEmpty()
            if (data.isNotEmpty()) {
                PushNotificationDisplayService.show(this, data)
                return
            }

            PushNotificationDisplayService.show(
                this,
                mapOf(
                    PushDataKeys.Title to (message.notification?.title ?: "ИКАР"),
                    PushDataKeys.Body to (message.notification?.body ?: "Новое сообщение")
                )
            )
        }.onFailure { error ->
            Log.e(LOG_TAG, "OnMessageReceived failed", error)
        }
    }

    companion object {
        private const val LOG_TAG = "IkarKotlinFcm"
    }
}
