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 = isPostPhoneAccelerate()
//        if (flag) {
//            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) {
            var extra: Int? = null
            if (id == PushCfg.ID_PHONE_ACCELERATE) {
                extra = RamMemoryEx.getMemoryUsage(FileApp.fContext).toInt()
            }
            FileApp.fContext.postActionNotification(id, eventParams, extra)
        }
    }

    private fun isPostPhoneAccelerate(): Boolean {
        val extra = RamMemoryEx.getMemoryUsage(FileApp.fContext)
        var log: String = ""
        if (extra < 60) {
            log = "isPostPhoneAccelerate ram<60 ram=$extra"
            EventHelper.event("pushCircleOrder_isPush ", log, eventParams = eventParams)
            return false
        }
        val memoryPushTime = FileApp.fContext.queryDataStoreBlock(createByActionId(PushCfg.ID_PHONE_ACCELERATE), 0)
        val interval = System.currentTimeMillis() - memoryPushTime
        val flag = interval > 20.minutes.toLong(DurationUnit.MILLISECONDS)
        if (!flag) {
            log = "isPostPhoneAccelerate interval < 20minus interval=$interval"
            EventHelper.event("pushCircleOrder_isPush ", log, eventParams = eventParams)
            return false
        }

        val isPush = PushManager.isPush(PushCfg.ID_PHONE_ACCELERATE)
        if (!isPush) {
            return false
        }

        FileApp.fContext.postActionNotification(PushCfg.ID_PHONE_ACCELERATE, eventParams, extra.toInt())

        return true
    }

}