package com.example.mydemo.strategy.fcm

import com.base.locationsharewhite.helper.GoogleSdkMgr
import java.util.Timer
import java.util.TimerTask

object TimerManager {
    private var taskTimer: Timer? = null
    var isTaskTimerActive: Boolean = false
        private set

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