package com.swiftcleaner.chovey.business.push

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.swiftcleaner.chovey.CleanApplication
import com.swiftcleaner.chovey.util.SPUtils
import com.swiftcleaner.chovey.util.Utils.toDate

class BatteryReceiver(
    private val block: (() -> Unit?)? = null
) : BroadcastReceiver() {

    companion object {
        private const val BATTERY_NOTIFICATION_STATUS_KEY = "batteryNotificationStatus"
        private const val BATTERY_NOTIFICATION_INTERVAL_KEY = "batteryNotificationInterval"
        private const val BATTERY_NOTIFICATION_COUNT_KEY = "batteryNotificationCount"
        private const val BATTERY_NOTIFICATION_CURRENT_KEY = "batteryNotificationCurrent"
        private const val BATTERY_NOTIFICATION_LAST_TIME_KEY = "batteryNotificationLastTime"

        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

        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()
        if (block == null) handle(context)
    }

    private fun handle(context: Context) {
        val batteryPct = level * 100 / scale.toFloat()
        if (batteryPct.toInt() > 21 && !isCharging) return

        val locks = SPUtils.getInstance().getInt(BATTERY_NOTIFICATION_STATUS_KEY, 1)
        if (locks != 1) return

        val interval = SPUtils.getInstance().getInt(BATTERY_NOTIFICATION_INTERVAL_KEY, 1) * 60 * 1000L
        val count = SPUtils.getInstance().getInt(BATTERY_NOTIFICATION_COUNT_KEY, 100)

        val currentKey = "${BATTERY_NOTIFICATION_CURRENT_KEY}_${context.toDate()}"
        val current = SPUtils.getInstance().getInt(currentKey)
        val lastTimeKey = "${BATTERY_NOTIFICATION_LAST_TIME_KEY}_${context.toDate()}"
        val lastTime = SPUtils.getInstance().getLong(lastTimeKey, 0)
        val currentTime = System.currentTimeMillis()
        if (currentTime - lastTime > interval && current < count) {
            SPUtils.getInstance().putInt(currentKey, current + 1)
            SPUtils.getInstance().putLong(lastTimeKey, currentTime)
            NotificationUtils.sendBatteryNotification(CleanApplication.context, batteryPct.toInt(), isCharging, "battery_receiver")
        }
    }
}