package com.koko.batteryinfo

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.os.Build

/**
 * 作者：马海钊
 * 时间：2025/2/11 11:59
 * 功能：
 */
class BatteryReceiver(
    private val block: (() -> Unit?)? = null
) : BroadcastReceiver() {

    companion object {

        var level = 0
        var scale = 0
        var voltage = 0
        var temperature = 0
        var technology = ""
        var health = 0
        var status = 0
        var mAh = 0f
        var isCharging = false

        @JvmStatic
        fun register(context: Context) {
            val intentFilter = IntentFilter().apply {
                addAction(Intent.ACTION_BATTERY_CHANGED)
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                context.registerReceiver(BatteryReceiver(), intentFilter, Context.RECEIVER_EXPORTED)
            } else {
                context.registerReceiver(BatteryReceiver(), intentFilter)
            }
        }
    }

    override fun onReceive(context: Context, intent: Intent) {
        if (Intent.ACTION_BATTERY_CHANGED != intent.action) return

        val batteryManager = context.getSystemService(Context.BATTERY_SERVICE) as BatteryManager
        level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0)
        scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 0)
        voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0)
        temperature = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0)
        technology = intent.getStringExtra(BatteryManager.EXTRA_TECHNOLOGY).toString()
        health = intent.getIntExtra(BatteryManager.EXTRA_HEALTH, 0)
        status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, BatteryManager.BATTERY_STATUS_UNKNOWN)
        isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL

        val chargeCounter = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CHARGE_COUNTER)
        val propertyCapacity = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
        if (chargeCounter != Int.MIN_VALUE && propertyCapacity != Int.MIN_VALUE) {
            mAh = (chargeCounter / (propertyCapacity.toFloat() / 100f)) / 1000f
        }
        block?.invoke()
    }

}