package com.koko.batteryinfo

import android.animation.ValueAnimator
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Color
import android.os.Bundle
import android.view.animation.LinearInterpolator
import androidx.activity.SystemBarStyle
import androidx.activity.addCallback
import androidx.activity.enableEdgeToEdge
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.didi.drouter.api.DRouter
import com.koko.batteryinfo.databinding.ActivityBatteryInfoBinding
import com.koko.drouter.ad.InterAdService
import com.koko.drouter.ad.NativeBatteryType
import com.koko.drouter.ad.NativeAdService
import com.koko.drouter.app.AppService
import java.math.BigDecimal
import java.math.RoundingMode

class BatteryInfoActivity : BaseActivity<ActivityBatteryInfoBinding>() {

    private var batteryReceiver: BatteryReceiver? = null

    override val binding: ActivityBatteryInfoBinding by lazy {
        ActivityBatteryInfoBinding.inflate(layoutInflater)
    }
    override fun initView() {
        useDefaultImmersive()
        registerReceiver()
        showNative()
        showInter()
    }

    override fun initListener() {
        super.initListener()
        onBackPressedDispatcher.addCallback {
            backMainShowAd()
        }
        binding.flBack.setOnClickListener { onBackPressedDispatcher.onBackPressed() }
    }

    private fun showInter() {
        val interAdService = DRouter.build(InterAdService::class.java).getService()

        interAdService.showInterAd(this) {
            startProgressAnimation(binding.tvBattery.text.toString().toInt())
        }
    }

    private fun backMainShowAd() {
        val interAdService = DRouter.build(InterAdService::class.java).getService()
        val appService = DRouter.build(AppService::class.java).getService()

        interAdService.showInterAdBack(this) {
            appService.finishToMainTop(this)
        }
    }

    private fun showNative() {
        val nativeService = DRouter.build(NativeAdService::class.java).getService()
        nativeService.showNative(this, binding.flAd, NativeBatteryType)
    }


    private fun useDefaultImmersive() {
        enableEdgeToEdge(SystemBarStyle.light(Color.TRANSPARENT, Color.TRANSPARENT))
        ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        batteryReceiver?.let { unregisterReceiver(batteryReceiver) }
    }

    private fun registerReceiver() {
        val intentFilter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
        batteryReceiver = BatteryReceiver { setBatteryInfo() }
        registerReceiver(batteryReceiver, intentFilter)
    }

    fun formatTime(totalMinutes: Int): String {
        val hours = totalMinutes / 60
        val minutes = totalMinutes % 60
        return "${hours}h${minutes}m"
    }

    private fun setBatteryInfo() {
        val percent = BatteryReceiver.level / BatteryReceiver.scale.toFloat()
        val remainingCapacity = BatteryReceiver.mAh * percent
        val wTime = (remainingCapacity / 6.0f).toInt()
        val battery = (percent * 100).toInt()
        val temperature = calculate(BatteryReceiver.temperature, 10)
        val voltage = calculate(BatteryReceiver.voltage, 1000)
        binding.tvBattery.text = "$battery"
        binding.tvEstimated.text = formatTime(wTime)
        binding.tvTemperature.text = "$temperature℃"
        binding.tvVoltage.text = "${voltage}V"
        binding.tvPower.text = "${(BatteryReceiver.mAh * percent).toInt()}mAh"
        binding.tvBatteryType.text = "${BatteryReceiver.technology}"
        binding.tvBatteryCapacity.text = "${BatteryReceiver.mAh.toInt()}mAh"
        binding.tvStatus.text = if (BatteryReceiver.isCharging) "Charging" else "Normal"

    }

    private fun startProgressAnimation(endProgress: Int) {
        ValueAnimator.ofInt(0, endProgress).apply {
            duration = 700
            interpolator = LinearInterpolator()
            addUpdateListener { animation ->
                val progress = animation.animatedValue as Int
                binding.pbBattery.setProgress(progress / 100f)
            }
        }.start()
    }

    private fun calculate(dividend: Int, divisor: Int): String {
        val bigDecimalDividend = BigDecimal(dividend)
        val bigDecimalDivisor = BigDecimal(divisor)
        // 执行除法操作，并保留一位小数，不四舍五入
        val result = bigDecimalDividend.divide(bigDecimalDivisor, 1, RoundingMode.DOWN)
        // 将结果转换回Double
        return result.toString()
    }
}