package com.base.scanqr.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.scanqr.bean.NotificationSendBean
import com.base.scanqr.bean.NotificationSendBean.Companion.POPUP_WHERE_BATTERY
import com.base.scanqr.bean.config.PopupConfigBean.Companion.popupConfigBean
import com.base.scanqr.fcm.notification.MyNotificationManager
import com.base.scanqr.helper.EventUtils
import com.base.scanqr.utils.AppPreferences
import com.base.scanqr.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 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 minute = 60 * 1000L
            val interval = popupConfigBean.popupBatteryInterval
            val passTime = System.currentTimeMillis() - batteryLastPushTime
            val flag = batteryLastPushTime == 0L || passTime > interval * minute

            if (!flag) {
                EventUtils.event("Notification_Error", "interval=$interval passTime=$passTime where=$POPUP_WHERE_BATTERY")
            }
            return flag
        }


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


    }

    private var currentBatteryPercentage = 0f

    override fun onReceive(context: Context, intent: Intent?) {
//        LogEx.logDebug(TAG, "onReceive")
        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 -> {
                LogEx.logDebug(TAG, "onReceive connected")

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


    }

}