package ru.forbion.f7cloud.feature.talk

import android.content.Context
import android.os.PowerManager
import android.util.Log

/** Keeps the device awake while a Talk call page is open (MIUI / Doze mitigation). */
class F7CallWakeLock(context: Context) {
    private val wakeLock: PowerManager.WakeLock =
        context.getSystemService(PowerManager::class.java)
            .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "f7cloud:talk_call")
            .apply { setReferenceCounted(false) }
    private var held = false

    fun updateForUrl(url: String?) {
        if (TalkHelper.isActiveCallUrl(url)) {
            acquire()
        } else {
            release()
        }
    }

    fun releaseAll() {
        release()
    }

    private fun acquire() {
        if (held) return
        runCatching {
            wakeLock.acquire(4 * 60 * 60 * 1000L)
            held = true
            Log.d(TAG, "Wake lock acquired for Talk call")
        }.onFailure {
            Log.w(TAG, "Wake lock acquire failed", it)
        }
    }

    private fun release() {
        if (!held) return
        runCatching {
            if (wakeLock.isHeld) wakeLock.release()
        }.onFailure {
            Log.w(TAG, "Wake lock release failed", it)
        }
        held = false
    }

    companion object {
        private const val TAG = "F7CallWakeLock"
    }
}
