package com.swiftcleaner.chovey.business.push

import com.swiftcleaner.chovey.CleanApplication
import com.swiftcleaner.chovey.GlobalConfig.ID_NOT_CLEANED
import com.swiftcleaner.chovey.GlobalConfig.KEY_CLEAN_LAST_TIME
import com.swiftcleaner.chovey.GlobalConfig.KEY_INSTALL_TIME
import com.swiftcleaner.chovey.GlobalConfig.KEY_NOT_CLEAN_TIME
import com.swiftcleaner.chovey.util.SPUtils
import java.util.Timer
import java.util.TimerTask

object NotCleanTimer {

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

    private const val cleanupLimitTime = 172800000
    private const val intervalTime = 14400000

    private var isActive = false

    fun start(delay: Long, period: Long) {
        synchronized(this) {
            if (!isActive) {
                cancelTimer()
                timer = Timer()
                timerTask = object : TimerTask() {
                    override fun run() {
                        val lastCleanTime = SPUtils.getInstance().getLong(KEY_CLEAN_LAST_TIME)
                        var time = lastCleanTime
                        if (time.toInt() == 0) {
                            time = SPUtils.getInstance().getLong(KEY_INSTALL_TIME)
                        }
                        val currentTime = System.currentTimeMillis()
                        if (currentTime - time >= cleanupLimitTime) {
                            val functionTime = SPUtils.getInstance().getLong(KEY_NOT_CLEAN_TIME, 0)
                            if (currentTime - functionTime > intervalTime) {
                                NotificationUtils.sendNotification(
                                    CleanApplication.context,
                                    ID_NOT_CLEANED,
                                    "timer_not_cleaned"
                                )
                                SPUtils.getInstance().putLong(KEY_NOT_CLEAN_TIME, currentTime)
                            }
                        }
                    }
                }
                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
    }
}