package com.humand.demo.modules.IncomingCallMessagingService.rn

import android.content.Intent
import android.os.Build
import com.facebook.react.ReactHost
import com.facebook.react.ReactInstanceEventListener
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.ReactContext
import com.facebook.react.bridge.WritableMap
import com.facebook.react.modules.core.DeviceEventManagerModule
import com.humand.demo.modules.IncomingCallMessagingService.common.CallPayload
import com.humand.demo.modules.IncomingCallMessagingService.common.Constants

object QueuedNotificationHolder {
    var pendingPayload: WritableMap? = null
}

// Handles delivery of incoming call push data to the React Native side
// once the call is answered on the native side
object RNNotificationBridge {
    fun handleIncomingCallEvents(reactInstance: ReactHost?, intent: Intent) {
        val payload = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            intent.getParcelableExtra(Constants.CALL_PAYLOAD, CallPayload::class.java)
        } else {
            @Suppress("DEPRECATION")
            intent.getParcelableExtra<CallPayload>(Constants.CALL_PAYLOAD)
        }

        if (payload != null && !payload.id.isBlank() && !payload.providerCallId.isBlank()) {
            val reactContext = reactInstance?.currentReactContext

            //Payload for the JS side
            val payloadMap = Arguments.createMap().apply {
                putString(Constants.CallPayloadKeys.ID, payload.id)
                putString(Constants.CallPayloadKeys.TYPE, payload.type.name)
                putString(Constants.CallPayloadKeys.PROVIDER_CALL_ID, payload.providerCallId)
                putBoolean(Constants.CallPayloadKeys.IS_GROUP, payload.isGroup ?: false)
                putString(Constants.CallPayloadKeys.INITIALIZATION_CONFIG, payload.initializationConfig)
            }
            if (reactContext != null && reactContext.hasActiveReactInstance()) {
                sendEventToJS(reactContext, payloadMap)
            } else {
                QueuedNotificationHolder.pendingPayload = payloadMap
                //Wait for React Native context initialization and send data to JS afterward
                if (reactInstance != null) {
                    reactInstance.addReactInstanceEventListener(
                        object : ReactInstanceEventListener {
                            override fun onReactContextInitialized(context: ReactContext) {
                                sendEventToJS(context, QueuedNotificationHolder.pendingPayload!!)
                                QueuedNotificationHolder.pendingPayload = null
                                reactInstance.removeReactInstanceEventListener(this)
                            }
                        }
                    )
                }
            }
        }
    }

    private fun sendEventToJS(reactContext: ReactContext, params: WritableMap) {
        reactContext
            .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
            .emit(Constants.RN_EVENT_NAME, params)
    }
}
