package com.humand.demo.modules.CallService

import android.annotation.SuppressLint
import android.content.Context
import android.os.PowerManager
import android.view.WindowManager
import com.facebook.react.bridge.ReactApplicationContext

/**
 * Manages proximity sensor and screen-on state based on whether any call video is active.
 */
class VideoSessionController(
    context: Context,
    private val reactContextProvider: () -> ReactApplicationContext?,
) {
    private val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager
    private var wakeLock: PowerManager.WakeLock? = null
    private var isVideoSessionActive = false
    private var isEarpieceRouteActive = false

    fun setVideoActive(active: Boolean) {
        if (isVideoSessionActive == active) return
        isVideoSessionActive = active
        updateScreenAndProximityState()
    }

    fun setEarpieceRouteActive(active: Boolean) {
        if (isEarpieceRouteActive == active) return
        isEarpieceRouteActive = active
        updateScreenAndProximityState()
    }

    fun reset() {
        isVideoSessionActive = false
        isEarpieceRouteActive = false
        keepScreenOn(false)
        disableProximitySensor()
    }

    private fun updateScreenAndProximityState() {
        keepScreenOn(isVideoSessionActive)
        val shouldEnableProximity = isEarpieceRouteActive && !isVideoSessionActive
        if (shouldEnableProximity) {
            enableProximitySensor()
        } else {
            disableProximitySensor()
        }
    }

    private fun keepScreenOn(enable: Boolean) {
        val activity = reactContextProvider()?.currentActivity ?: return
        activity.runOnUiThread {
            if (enable) {
                activity.window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
            } else {
                activity.window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
            }
        }
    }

    @SuppressLint("WakelockTimeout")
    private fun enableProximitySensor() {
        val lock = wakeLock ?: powerManager.newWakeLock(
            PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK,
            "HumandCall:Proximity",
        ).also { wakeLock = it }

        if (!lock.isHeld) {
            try {
                lock.acquire()
            } catch (_: RuntimeException) {
            }
        }
    }

    private fun disableProximitySensor() {
        if (wakeLock?.isHeld == true) {
            try {
                wakeLock?.release()
            } catch (_: RuntimeException) {
            }
        }
    }
}
