package com.base.appzxhy.fcm.receiver

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.base.appzxhy.bean.NotificationSendBean
import com.base.appzxhy.bean.NotificationSendBean.Companion.POPUP_WHERE_BATTERY
import com.base.appzxhy.bean.config.PopupConfigBean.Companion.popupConfigBean
import com.base.appzxhy.fcm.notification.MyNotificationManager
import com.base.appzxhy.helper.EventUtils
import com.base.appzxhy.utils.AppPreferences
import com.base.appzxhy.utils.KotlinExt.currentDate
import com.base.appzxhy.utils.LogEx
import kotlin.math.absoluteValue

/**
 *电量监听
 */
class BatteryStatusReceiver() : BroadcastReceiver() {


    companion object {

        private val TAG = "BatteryStatusReceiver"

        fun registerBatteryStatusReceiver(context: Context) {
            val intentFilter = IntentFilter().apply {
                addAction(Intent.ACTION_BATTERY_CHANGED)
                addAction(Intent.ACTION_POWER_CONNECTED)
                addAction(Intent.ACTION_POWER_DISCONNECTED)
            }
            val applicationContext = context.applicationContext
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                applicationContext.registerReceiver(
                    BatteryStatusReceiver(),
                    intentFilter,
                    Context.RECEIVER_EXPORTED
                )
            } else {
                applicationContext.registerReceiver(BatteryStatusReceiver(), intentFilter)
            }
        }


        /**
         * 当前天推送数量
         */
        private var todayBatteryPush = 0
            get() {
                return AppPreferences.getInstance().getInt("todayBatteryPush_${currentDate()}", field)
            }
            set(value) {
                field = value
                AppPreferences.getInstance().put("todayBatteryPush_${currentDate()}", value, true)
            }

        /**
         * 上次成功推送
         */
        private var batteryLastPushTime = 0L
            get() {
                return AppPreferences.getInstance().getLong("batteryLastPushTime", field)
            }
            set(value) {
                field = value
                AppPreferences.getInstance().put("batteryLastPushTime", value, true)
            }

        /**
         * 电池电量是否可推送
         * 总的限制条件判断后才判断
         */
        fun canBatteryStatusReceiverPush(): Boolean {

            if (!popupConfigBean.batteryS) return false

            val popupBatteryCount = popupConfigBean.popupBatteryValue
            val flag1 = todayBatteryPush <= popupBatteryCount

            val minute = 60 * 1000L

            val interval = popupConfigBean.popupBatteryInterval
            val passTime = System.currentTimeMillis() - batteryLastPushTime
            val flag2 = batteryLastPushTime == 0L || passTime > interval * minute


            val flag = flag1 && flag2

            if (!flag) {
                EventUtils.event(
                    "Notification_Error", "todayBatteryPush=$todayBatteryPush " +
                            "popupBatteryCount=$popupBatteryCount where=$POPUP_WHERE_BATTERY"
                )
                LogEx.logDebug(
                    "canSendNotification", "Notification_Error todayBatteryPush=$todayBatteryPush " +
                            "popupBatteryCount=$popupBatteryCount where=$POPUP_WHERE_BATTERY"
                )
            }
            return flag
        }


        /**
         * 推送成功后保存值
         */
        fun saveBatteryPushedData() {
            todayBatteryPush += 1
            batteryLastPushTime = System.currentTimeMillis()
        }


    }

    private var currentBatteryPercentage = 0f

    override fun onReceive(context: Context, intent: Intent?) {
        val action = intent?.action

        when (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

                //避免频繁触发
                val changeValue = currentBatteryPercentage - batteryPercentage

                if (batteryPercentage < popupConfigBean.popupBatteryValue && changeValue.absoluteValue >= 1f) {
                    //推送次数没有达到限制并且展示的最小时间间隔大于配置时间(分钟)

                    LogEx.logDebug(TAG, "onReceive changed")
                    val sendBean = NotificationSendBean(context, POPUP_WHERE_BATTERY,
                        canSend = {
                            canBatteryStatusReceiverPush()
                        },
                        sendSuccess = {
                            saveBatteryPushedData()
                        })
                    MyNotificationManager.submitSendBean(sendBean)
                }

                currentBatteryPercentage = batteryPercentage
            }

            Intent.ACTION_POWER_CONNECTED -> {

                val sendBean = NotificationSendBean(context, POPUP_WHERE_BATTERY,
                    canSend = {
                        canBatteryStatusReceiverPush()
                    },
                    sendSuccess = {
                        saveBatteryPushedData()
                    })
                MyNotificationManager.submitSendBean(sendBean)
            }
        }


    }

}