package com.base.locationsharewhite.fcm

import com.base.locationsharewhite.fcm.NotificationUiUtil.sendNotificationIfCan
import com.base.locationsharewhite.fcm.PopupConstObject.popupConfigBean
import com.base.locationsharewhite.fcm.receiver.ScreenStatusReceiver
import com.base.locationsharewhite.helper.MyApplication
import com.base.locationsharewhite.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")
                        sendNotificationIfCan(MyApplication.appContext, PopupConstObject.POPUP_WHERE_TIMBER, null)
                    }
                }
            }
            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()
                    )
                }
            }
        }
    }
}