package com.zxhyis.toolss.common.notification

import com.zxhyis.toolss.FileApp
import com.zxhyis.toolss.ad.EventHelper
import com.zxhyis.toolss.ad.PushManager
import com.zxhyis.toolss.ad.bean.EventParams
import com.zxhyis.toolss.ad.bean.PushCfg
import com.zxhyis.toolss.ad.bean.PushCfg.Companion.ID_LOW_RAM_PUSH
import com.zxhyis.toolss.ad.createByActionId
import com.zxhyis.toolss.ad.queryDataStoreBlock
import com.zxhyis.toolss.common.notification.NotificationHelper.postActionNotification
import com.zxhyis.toolss.logic.LogEx
import com.zxhyis.toolss.logic.RamMemoryEx
import java.util.TimerTask
import kotlin.time.Duration.Companion.minutes
import kotlin.time.DurationUnit

/**
 * 循环推送任务
 */
class NotificationTimerTask(val eventParams: EventParams?) : TimerTask() {

    private val TAG = "NotificationTimerTask"


    override fun run() {
        oneShotNotification()
    }


    fun oneShotNotification(noLimit: Boolean = false) {
        //内存低于阀值推送
        val flag = postRamLower60()
        if (flag) {
            val log = "postRamLower60 isPush=$flag"
            EventHelper.event("pushCircleOrder_isPush", log, eventParams = eventParams)
            val extra = RamMemoryEx.getMemoryUsage(FileApp.fContext).toInt()
            FileApp.fContext.postActionNotification(ID_LOW_RAM_PUSH, eventParams, extra)
            return
        }

        val id = NotificationHelper.getPresentPushId()
        val isPush = PushManager.isPush(id, eventParams = eventParams)
        val log = "isPush=$isPush " + "id=${id} "
        EventHelper.event("pushCircleOrder_isPush", log, eventParams = eventParams)
        LogEx.logDebug(TAG, log)
        if (isPush || noLimit) {
            FileApp.fContext.postActionNotification(id, eventParams)
        }
    }

    private fun postRamLower60(): Boolean {
        val ss = RamMemoryEx.getMemoryUsage(FileApp.fContext)
        val memoryPushTime = FileApp.fContext.queryDataStoreBlock(createByActionId(PushCfg.ID_LOW_RAM_PUSH), 0)
        val flag = System.currentTimeMillis() - memoryPushTime > 20.minutes.toLong(DurationUnit.MILLISECONDS)
        val isPush = PushManager.isPush(ID_LOW_RAM_PUSH)
        if (ss > 60 && flag && isPush) {
            FileApp.fContext.postActionNotification(PushCfg.ID_LOW_RAM_PUSH)
            return true
        }
        return flag
    }

}