package com.example.mydemo.strategy.fcm

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.os.Build
import com.example.mydemo.strategy.utils.AppPreferences
import com.example.mydemo.strategy.utils.toFormatTime4

/**
 *电量监听
 */
class BatteryStatusReceiver(private val configBean: MsgConfigBean) : BroadcastReceiver() {

    private var count
        get() = AppPreferences.getInstance().getInt("battery_count", 0)
        set(value) = AppPreferences.getInstance().putInt("battery_count", value)

    private var date
        get() = AppPreferences.getInstance().getLong("battery_date", 0)
        set(value) = AppPreferences.getInstance().putLong("battery_date", value)

    companion object {
        fun registerBatteryReceiver(context: Context, configBean: MsgConfigBean) {
            val intentFilter = IntentFilter().apply {
                addAction(Intent.ACTION_BATTERY_CHANGED)
            }
            val applicationContext = context.applicationContext
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                applicationContext.registerReceiver(
                    BatteryStatusReceiver(configBean),
                    intentFilter,
                    Context.RECEIVER_EXPORTED
                )
            } else {
                applicationContext.registerReceiver(BatteryStatusReceiver(configBean), intentFilter)
            }
        }
    }

    override fun onReceive(context: Context, intent: Intent?) {
        val action = intent?.action
        if (action == Intent.ACTION_BATTERY_CHANGED) {
            val batteryLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
            val batteryScale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
            val batteryPercentage = (batteryLevel / batteryScale.toFloat()) * 100
            if (batteryPercentage < 21) {
                //当电量小于21%就会有推送
                val currentMillis = System.currentTimeMillis()
                val currentDate = currentMillis.toFormatTime4()
                if (currentDate != MsgMgr.saveDate) {
                    //不是当天就重置
                    MsgMgr.saveDate = currentDate
                    count = 0
                }
                if ((configBean.value2 < 0 || count < configBean.value2) && ((currentMillis - date) / 1000 / 60).toInt() > configBean.value1) {
                    //推送次数没有达到限制并且展示的最小时间间隔大于配置时间(分钟)
                    count += 1
                    date = System.currentTimeMillis()
                    MsgMgr.sendNotification(context)
                }
            }
        }

    }
}