package com.swiftcleaner.chovey.business.push

import com.swiftcleaner.chovey.CleanApplication
import com.swiftcleaner.chovey.util.SPUtils
import java.util.Timer
import java.util.TimerTask

object PushTimer {

    private var timer: Timer? = null
    private var timerTask: TimerTask? = null

    private var scheduleCount: Int = 1 // 任务执行次数计数器
    private var scheduleTime: Long = 0L
    private var lastTime: Long = 0L

    private var isActive = false

    fun start(delay: Long, period: Long) {
        synchronized(this) {
            if (!isActive) {
                cancelTimer()
                timer = Timer()
                timerTask = object : TimerTask() {
                    override fun run() {
                        if (UnlockReceiver.isScreenOn && !UnlockReceiver.isLock && CleanApplication.APP_STATE != 1) {
                            NotificationUtils.sendNotification(
                                CleanApplication.context,
                                "timer"
                            )
                        }
                    }
                }
                timer?.schedule(timerTask, delay, period)
                isActive = true
            }
        }
    }

    fun stop() {
        synchronized(this) {
            if (isActive)
                cancelTimer()
        }
    }

    private fun cancelTimer() {
        timerTask?.cancel()
        timer?.cancel()
        timer?.purge()
        isActive = false
        scheduleCount = 1
    }

    private fun scheduleNextInterval() {
        val timerIntervalSt = SPUtils.getInstance().getInt("timerIntervalSt", 3)
        val timerIntervalNd = SPUtils.getInstance().getInt("timerIntervalNd", 5)
        val timerIntervalRd = SPUtils.getInstance().getInt("timerIntervalRd", 6)
        val timerIntervalRth = SPUtils.getInstance().getInt("timerIntervalRth", 8)
        val timerIntervalFth = SPUtils.getInstance().getInt("timerIntervalFth", 10)
        scheduleTime = when (scheduleCount) {
            2 -> timerIntervalNd * 60 * 1000L
            3 -> timerIntervalRd * 60 * 1000L
            4 -> timerIntervalRth * 60 * 1000L
            5 -> timerIntervalFth * 60 * 1000L
            else -> {
                timerIntervalSt * 60 * 1000L
            }
        }
    }
}