package com.zxdemo.utils

import android.util.Log
import com.swiftcleaner.chovey.model.bean.Global.NOTIFICATION_WHERE_TIMBER
import com.zxdemo.ZxApplication.Companion.isAppInForeground
import com.zxdemo.ZxApplication.Companion.isDeviceLocked
import com.zxdemo.ZxApplication.Companion.isScreenOn
import com.zxdemo.notity.NotificationUtils
import com.zxdemo.ZxApplication
import java.util.Timer
import java.util.TimerTask


object GlobalTimer {

    private var instance: GlobalTimer? = null
    private var taskTimer: Timer? = null
    private var isTimerActive = false

    // 单例模式获取实例
    fun getInstance(): GlobalTimer {
        if (instance == null) {
            instance = GlobalTimer
        }
        return instance!!
    }

    // 调度任务
    fun scheduleTask(delay: Long, period: Long) {
        synchronized(GlobalTimer::class) {
            ensureTimerIsStopped() // 确保定时器未运行
            taskTimer = Timer() // 创建新的 Timer 实例
            val task = object : TimerTask() {
                override fun run() {
                    // 确保设备处于交互状态，未锁定，且应用未暂停
                    NotificationUtils.sendNotification(ZxApplication.context, NOTIFICATION_WHERE_TIMBER)
                }
            }
            taskTimer!!.schedule(task, delay, period) // 调度任务
            isTimerActive = true // 设置定时器状态为活跃
        }
    }

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

    // 停止任务定时器
    fun stopTaskTimer() {
        synchronized(GlobalTimer::class) {
            ensureTimerIsStopped() // 停止定时器
        }
    }

    // 检查任务定时器是否活跃
    fun isTaskTimerActive(): Boolean {
        return isTimerActive
    }
}
