package com.base.locationsharewhite.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.base.locationsharewhite.fcm.PopupConstObject.POPUP_WHERE_BATTERY
import com.base.locationsharewhite.fcm.PopupConstObject.popup_battery_count
import com.base.locationsharewhite.fcm.PopupConstObject.popup_battery_interval
import com.base.locationsharewhite.helper.EventUtils
import com.base.locationsharewhite.utils.AppPreferences
import com.base.locationsharewhite.utils.KotlinExt.currentDate
import com.base.locationsharewhite.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)
            }
            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 {

            val popupBatteryCount = AppPreferences.getInstance().getString(popup_battery_count, "20").toInt()
            val flag1 = todayBatteryPush <= popupBatteryCount

            val minute = 60 * 1000L
            val default = 60 * minute

            val interval = AppPreferences.getInstance().getString(popup_battery_interval, default.toString()).toLong()
            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(where: String, actionId: String) {
            if (where == POPUP_WHERE_BATTERY) {
                todayBatteryPush += 1
                batteryLastPushTime = System.currentTimeMillis()
            }
        }


    }

    private var currentBatteryPercentage = 0f

    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

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

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

            currentBatteryPercentage = batteryPercentage
        }

    }

}