package com.tgv.malware.business.push.timer

import android.util.Log
import com.tgv.malware.MyApplication
import com.tgv.malware.bean.push.NotificationSendBean
import com.tgv.malware.bean.push.NotificationSendBean.Companion.POPUP_WHERE_TIMER
import com.tgv.malware.bean.config.PopupConfigBean.Companion.popupConfigBean
import com.tgv.malware.business.push.notification.MyNotificationManager
import com.tgv.malware.business.push.receiver.ScreenStatusReceiver
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 createNewTask(): TimerTask {
        val task: TimerTask = object : TimerTask() {
            override fun run() {
                Log.e(TAG, "TimerTask run")
                // 确保设备处于交互状态，未锁定，且应用未暂停
                val deviceRunning = (ScreenStatusReceiver.isDeviceInteractive &&
                        !ScreenStatusReceiver.isSecureLockActive &&
                        MyApplication.PAUSED_VALUE != 1)

                if (deviceRunning || popupConfigBean.popupForegroundCanPush) {
                    MyNotificationManager.submitSendBean(NotificationSendBean(MyApplication.appContext, POPUP_WHERE_TIMER))
                }
            }
        }
        return task
    }

    fun scheduleTask(delay: Long, period: Long) {
        synchronized(TimerManager::class.java) {
            ensureTimerIsStopped() // 确保定时器未运行
            taskTimer = Timer() // 创建新的 Timer 实例
            taskTimer?.schedule(createNewTask(), 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 * 1000).toLong(),
                        (timerInterval * 60 * 1000).toLong()
                    )
                }
            }
        }
    }
}