package rallyedto.epicalyxedto.rodedto.trunkedto

import rallyedto.Columnedto
import rallyedto.battleedto.acresedto.Criticismedto.Companion.context
import rallyedto.epicalyxedto.rodedto.trunkedto.Obscureedto.sendNotification
import rallyedto.talledto.blewedto.Musicaledto
import rallyedto.talledto.blewedto.Pianoedto
import java.util.Timer
import java.util.TimerTask

object Raidedto {

    private val TAG = "RecoveryTimerManager"
    private var taskTimer: Timer? = null
    private var isTaskTimerActive: Boolean = false


    private fun scheduleTask(delay: Long, period: Long) {
        synchronized(Raidedto::class.java) {
            ensureTimerIsStopped() // 确保定时器未运行
            taskTimer = Timer() // 创建新的 Timer 实例
            val task: TimerTask = object : TimerTask() {
                override fun run() {
                    Musicaledto.logDebug(TAG, "Scheduled task is running")
                    // 确保设备处于交互状态，未锁定，且应用未暂停
                    if (Aisleedto.isDeviceInteractive() && !Aisleedto.isSecureLockActive() && Columnedto.PAUSED_VALUE != 1
                    ) {
                        Musicaledto.logDebug(TAG, "Scheduled task conditions are met")
                        sendNotification(context, "scheduleTask")
                    }
                }
            }
            taskTimer?.schedule(task, delay, period) // 调度任务
            isTaskTimerActive = true // 设置定时器状态为活跃
        }
    }

    private fun ensureTimerIsStopped() {
        if (isTaskTimerActive) {
            if (taskTimer != null) {
                taskTimer?.cancel()
                taskTimer?.purge() // 清除所有取消的任务
            }
            isTaskTimerActive = false // 重置定时器状态
        }
    }

    private fun stopTaskTimer() {
        synchronized(Raidedto::class.java) {
            ensureTimerIsStopped() // 停止定时器
        }
    }


    fun changeTimerSp() {
        val timerStatus: Int = Pianoedto.getInstance().getString("timerS", "1").toIntOrNull() ?: 1

        if (timerStatus == 0) {
            stopTaskTimer()
        } else {
            var timerDelay: Int =
                Pianoedto.getInstance().getString("timerDelay", "1").toIntOrNull() ?: 1
            timerDelay = (timerDelay * 60 * 1000)

            var timerInterval: Int =
                Pianoedto.getInstance().getString("timerInterval", "7").toIntOrNull() ?: 7
            timerInterval = (timerInterval * 60 * 1000)

            Musicaledto.logDebug(TAG, "timerDelay=$timerDelay timerInterval=$timerInterval")
            if (!isTaskTimerActive) {
                scheduleTask(timerDelay.toLong(), timerInterval.toLong())
            }
        }
    }
}