package com.zxdemo.receiver

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.BatteryManager
import android.os.Build
import android.util.Log
import androidx.annotation.RequiresApi
import com.zxdemo.notity.NotificationUtils
import com.zxdemo.utils.SpUtils
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit

class BatteryStatusReceiver() : BroadcastReceiver() {
    @RequiresApi(Build.VERSION_CODES.O)
    override fun onReceive(context: Context?, batteryIntent: Intent?) {
        val level = batteryIntent?.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) ?: -1
        val scale = batteryIntent?.getIntExtra(BatteryManager.EXTRA_SCALE, -1) ?: -1
        val state = batteryIntent?.getIntExtra(BatteryManager.EXTRA_STATUS, -1) ?: -1

        val now =
            batteryIntent?.getIntExtra(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW.toString(), -1)
                ?: -1
        val health = batteryIntent?.getIntExtra(BatteryManager.EXTRA_HEALTH, -1) ?: -1
        val voltage = batteryIntent?.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1) ?: -1
        val temperature = batteryIntent?.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1) ?: -1
        val technology = batteryIntent?.getStringExtra(BatteryManager.EXTRA_TECHNOLOGY) ?: "Unknown"

        val batteryPct = level * 100 / scale.toFloat()


        val intervalTime = SpUtils.getInstance().getInt("batteryNotificationInterval", 5)
        var current = LocalDateTime.now()
        var lastTime =
            SpUtils.getInstance().getString("NOTICE_BATTERY_TIME", "")
        var parsedDateTime = current
        if (lastTime != "") {
            parsedDateTime =
                LocalDateTime.parse(lastTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"))
        }
        var batteryNotificationStatus = SpUtils.getInstance().getInt("batteryNotificationStatus", 0)
        val minutesBetween = ChronoUnit.MINUTES.between(parsedDateTime, current)
//        Log.d("TAG", "onReceive:电池 $minutesBetween   $intervalTime")

        if ((batteryNotificationStatus == 1 && (minutesBetween > intervalTime && minutesBetween.toInt() == 0)) && (state == BatteryManager.BATTERY_STATUS_CHARGING || (level < 20 && level > 10))) {
            Log.d("TAG", "onReceive: 电池推送")
            if (context != null) {
                NotificationUtils.sendNotification(
                    context,
                    "showNotification",
                    "receive_battery"
                )
                SpUtils.getInstance().putString(
                    "NOTICE_BATTERY_TIME",
                    current.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"))
                )
            }
        }
    }


}