package com.base.datarecovery.receiver

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

class BatteryReceiver(private val change: () -> Unit) : BroadcastReceiver() {
    companion object {
        var level = 0
        var scale = 0
        var voltage = 0
        var temperature = 0
        var mAh = 0f
        var health = 0
        var status = 0
        var technology = "" //获取电池技术支持
    }

    override fun onReceive(context: Context, intent: Intent) {
        if (intent.action == Intent.ACTION_BATTERY_CHANGED) {
            level = intent.getIntExtra("level", 0)
            scale = intent.getIntExtra("scale", 0)
            voltage = intent.getIntExtra("voltage", 0)
            temperature = intent.getIntExtra("temperature", 0)
            technology = intent.getStringExtra("technology").toString()
            status = intent.getIntExtra("status", BatteryManager.BATTERY_STATUS_UNKNOWN)
            health = intent.getIntExtra("health", BatteryManager.BATTERY_HEALTH_UNKNOWN)

            val batteryManager = context.getSystemService(Context.BATTERY_SERVICE) as? BatteryManager ?: return
            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
            }
            change.invoke()
        }
    }
}