package com.base.appzxhy.fcm.timer

import com.base.appzxhy.MyApplication
import com.base.appzxhy.bean.NotificationSendBean
import com.base.appzxhy.bean.NotificationSendBean.Companion.POPUP_WHERE_TIMER
import com.base.appzxhy.bean.config.PopupConfigBean.Companion.popupConfigBean
import com.base.appzxhy.fcm.notification.MyNotificationManager
import com.base.appzxhy.fcm.receiver.ScreenStatusReceiver
import com.base.appzxhy.utils.LogEx.logDebug
import java.util.Timer
import java.util.TimerTask


class TimerManager private constructor() {

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

    fun scheduleTask(delay: Long, period: Long) {
        logDebug(TAG, "scheduleTask")
        synchronized(TimerManager::class.java) {
            ensureTimerIsStopped() // 确保定时器未运行
            taskTimer = Timer() // 创建新的 Timer 实例
            val task: TimerTask = object : TimerTask() {
                override fun run() {
                    logDebug(TAG, "scheduleTask run")
                    // 确保设备处于交互状态，未锁定，且应用未暂停
                    if (ScreenStatusReceiver.isDeviceInteractive
                        && !ScreenStatusReceiver.isSecureLockActive
                        && MyApplication.PAUSED_VALUE != 1
                    ) {
                        logDebug(TAG, "scheduleTask send")
                        val sendBean =
                            NotificationSendBean(MyApplication.appContext, POPUP_WHERE_TIMER, canSend = { true }, sendSuccess = {})
                        MyNotificationManager.submitSendBean(sendBean)
                    }
                }
            }
            taskTimer?.schedule(task, delay, period) // 调度任务
            isTaskTimerActive = true // 设置定时器状态为活跃
        }
    }

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

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

    companion object {

        private val instance: TimerManager by lazy((LazyThreadSafetyMode.SYNCHRONIZED)) { TimerManager() }


        fun changeTimer() {

            if (!popupConfigBean.timerS) {
                instance.stopTaskTimer()
            } else {
                val timerDelay: Int = popupConfigBean.timerDelay
                val timerInterval: Int = popupConfigBean.timerInterval

                val isTaskTimerActive = instance.isTaskTimerActive
                if (!isTaskTimerActive) {
                    instance.scheduleTask(
                        (timerDelay * 60 * 1000).toLong(),
                        (timerInterval * 60 * 1000).toLong()
                    )
                }
            }
        }
    }
}