package com.base.datarecovery.fcm

import com.base.datarecovery.BuildConfig
import com.base.datarecovery.MyApplication
import com.base.datarecovery.fcm.NotificationUtil.sendNotification
import com.base.datarecovery.help.BaseApplication.Companion.context
import com.base.datarecovery.utils.AppPreferences
import com.base.datarecovery.utils.LogEx
import java.util.Timer
import java.util.TimerTask

object RecoveryTimerManager {

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


    private fun scheduleTask(delay: Long, period: Long) {
        synchronized(RecoveryTimerManager::class.java) {
            ensureTimerIsStopped() // 确保定时器未运行
            taskTimer = Timer() // 创建新的 Timer 实例
            val task: TimerTask = object : TimerTask() {
                override fun run() {
                    LogEx.logDebug(TAG, "Scheduled task is running")
                    // 确保设备处于交互状态，未锁定，且应用未暂停
                    if (ScreenStatusReceiver.isDeviceInteractive() && !ScreenStatusReceiver.isSecureLockActive() && MyApplication.PAUSED_VALUE != 1
                    ) {
                        LogEx.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(RecoveryTimerManager::class.java) {
            ensureTimerIsStopped() // 停止定时器
        }
    }


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

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

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

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