package com.adealink.weparty.call.util

import android.content.Context
import android.os.PowerManager
import com.adealink.frame.log.Log
import com.adealink.weparty.call.constant.TAG_CALL_DEVICE
import com.tencent.qcloud.tuikit.tuicallkit.common.utils.DeviceUtils

class ScreenWakeupHelper(val context: Context) {

    companion object {
        const val TAG_WAKE_LOCK = "call-1v1:WAKE_LOCK"

        const val BACKGROUND_LOCK = PowerManager.PARTIAL_WAKE_LOCK
        const val FOREGROUND_WAKE_FLAG = PowerManager.SCREEN_BRIGHT_WAKE_LOCK
    }

    private var wakeLock: PowerManager.WakeLock? = null

    fun wakeupIfPowerOff(timeout: Long = 30 * 1000L): ScreenWakeupHelper {
        try {
            val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager
            if (powerManager.isInteractive) {
                Log.d(TAG_CALL_DEVICE, "wakeupIfPowerOff return, for screen power on")
                return this
            }
            val isBackground = DeviceUtils.isAppRunningForeground(context)
            Log.d(TAG_CALL_DEVICE, "wakeupIfPowerOff(), timeout:$timeout, isBackground:$isBackground")
            acquireWakeLock(powerManager, if (isBackground) BACKGROUND_LOCK else FOREGROUND_WAKE_FLAG, timeout)
        } catch (e: Exception) {
            Log.e(TAG_CALL_DEVICE, "wakeupIfPowerOff() fail, for ${e.message}", e)
        }
        return this
    }

    private fun acquireWakeLock(powerManager: PowerManager, levelAndFlags: Int, timeout: Long) {
        val pm = powerManager ?: return
        if (wakeLock == null) {
            wakeLock = pm.newWakeLock(
                levelAndFlags
                        or PowerManager.ACQUIRE_CAUSES_WAKEUP
                        or PowerManager.ON_AFTER_RELEASE,
                TAG_WAKE_LOCK
            )
            wakeLock?.setReferenceCounted(false)
        }
        if (wakeLock?.isHeld == false) {
            wakeLock?.acquire(timeout)
        }
    }

    fun releaseLock() {
        releaseWakeLock()
    }

    private fun releaseWakeLock() {
        if (wakeLock?.isHeld == true) {
            wakeLock?.release()
            wakeLock = null
        }
    }
}