package rowedto.jockeyedto.sheetedto.atticedto.peakedto.affinityedto.jacketedto

import android.annotation.SuppressLint
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Color
import android.os.BatteryManager
import androidx.activity.addCallback
import androidx.core.view.updatePadding
import com.base.datarecovery.databinding.WinedtoBinding
import rowedto.jockeyedto.sheetedto.atticedto.Softedto
import rowedto.jockeyedto.sheetedto.balsamedto.formaledto.orientationedto.Patedto.showExitFunctionDialog
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Dynamicedto.BATTERY_INFO
import rowedto.jockeyedto.sheetedto.knewedto.economicedto.copyrightedto.Crossingedto
import rowedto.jockeyedto.sheetedto.meanedto.Loungeedto
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Spareedto
import rowedto.jockeyedto.sheetedto.strangeedto.pyramidedto.particlesedto.Scandaledto
import kotlin.math.abs


class Depressionedto : Crossingedto<WinedtoBinding>() {

    private val TAG = "BatteryActivity"

    override val binding: WinedtoBinding by lazy {
        WinedtoBinding.inflate(layoutInflater)
    }
    private lateinit var batteryReceiver: Loungeedto

    private lateinit var mBatteryManager: BatteryManager

    @SuppressLint("SetTextI18n")
    override fun initView() {
        Spareedto.setStatusBarLightMode(this, true)
        Spareedto.setStatusBarColor(this, Color.parseColor("#FAFAFA"))
        binding.root.updatePadding(top = Spareedto.getStatusBarHeight())

        batteryReceiver = Loungeedto {
            updateUi()
        }
        registerReceiver(batteryReceiver, IntentFilter().apply {
            addAction("android.intent.action.BATTERY_CHANGED")
        })

        mBatteryManager = getSystemService(BATTERY_SERVICE) as BatteryManager

//        getAverageCurrent()
//
//        lifecycleScope.launch(Dispatchers.Main) {
//            currentFlow.collectLatest {
//                binding.collegeedto.text = "${it}mA"
//            }
//        }
//        lifecycleScope.launch(Dispatchers.Main) {
//            averageFlow.collectLatest {
//                binding.governmentedto.text = "${it}mA"
//            }
//        }

        Scandaledto.admobMaxShowNativeAd(this, binding.breatheedto, 2)
    }

    override fun initListener() {
        super.initListener()
        onBackPressedDispatcher.addCallback {
            showExitFunctionDialog { showAd ->
                if (showAd) {
                    Scandaledto.admobMaxShowInterstitialAd(this@Depressionedto) {
                        finishToMain()
                    }
                } else {
                    finishToMain()
                }
            }
        }
        binding.conditionedto.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        binding.flairedto.setOnClickListener {
            startActivity(Intent(this, Softedto::class.java).apply {
                putExtra("from", BATTERY_INFO)
            })
            finish()
        }
    }

    @SuppressLint("SetTextI18n")
    private fun updateUi() {
        val temperature = Loungeedto.temperature / 10f
        binding.arrangeedto.text = format(temperature) + " °C"

        binding.selleredto.text = "${format((Loungeedto.voltage / 1000f))} mV"

        binding.ruleedto.text = Loungeedto.technology

        val capacity = Loungeedto.mAh.toInt()
        binding.poleedto.text = "$capacity mAh"

        val currentNow = mBatteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW)
        binding.collegeedto.text = "${getFirstThreeDigits(currentNow * 100)} mA"

        val currentAverage: Int = mBatteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_AVERAGE)
        binding.governmentedto.text = "${getFirstThreeDigits(currentAverage * 100)} mA"

        val hm = (capacity.toFloat() / getFirstThreeDigits(currentNow * 100).toFloat())

        binding.compoundedto.text = abs(hm.toInt()).toString()
        binding.helloedto.text = abs(((hm - hm.toInt()) * 60).toInt()).toString()
    }

    private fun getFirstThreeDigits(number: Int): String {
        if (number == 0) {
            return "0"
        }
        return number.toString().take(3)
    }

    private fun format(float: Float): String {
        return "%.1f".format(float)
    }

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


//    @SuppressLint("PrivateApi")
//    fun getBatteryFilePath(): String {
//        val systemProperties = Class.forName("android.os.SystemProperties")
//        val getMethod = systemProperties.getDeclaredMethod("get", String::class.java)
//        val platName = getMethod.invoke(null, "ro.hardware") as String
//
//        Dishedto.logDebug(TAG, "platName=$platName")
//        val filePath: String = if (platName.startsWith("mt") || platName.startsWith("MT")) {
//            "/sys/class/power_supply/battery/device/FG_Battery_CurrentConsumption"
//            // MTK平台该值不区分充放电，都为负数
//        } else if (platName.startsWith("qcom")) {
//            "/sys/class/power_supply/battery/current_now"
//        } else if (platName.startsWith("exynos"))
//            "/sys/class/power_supply/battery/BatteryAverageCurrent"
//        else {
//            ""
//        }
//        Dishedto.logDebug(TAG, "filePath=$filePath")
//        return filePath
//    }


//    var mAverageFlow = MutableSharedFlow<Float>()
//    val averageFlow: SharedFlow<Float> = mAverageFlow
//
//    var mCurrentFlow = MutableSharedFlow<Int>()
//    var currentFlow: SharedFlow<Int> = mCurrentFlow


//    private fun getAverageCurrent(filePath: String = getBatteryFilePath()) {
//        var sum = 0
//        var loopCount = 0
//        lifecycleScope.launch(Dispatchers.IO) {
//            while (isActive) {
//                val currentValue = readFileValue(filePath)
//                mCurrentFlow.emit(currentValue)
//                sum += currentValue
//                loopCount++
//                val average = sum / loopCount.toFloat()
//                mAverageFlow.emit(average)
//                delay(150)
//            }
//        }
//    }


//    private fun readFileValue(filePath: String): Int {
//        var value = 0
//        var br: BufferedReader? = null
//        try {
//            br = BufferedReader(FileReader(filePath))
//            val line = br.readLine()
//            value = line?.toInt() ?: 0
//            Dishedto.logDebug(TAG, "readFileValue value=$value")
//        } catch (e: Exception) {
//            e.printStackTrace()
//        } finally {
//            br?.close()
//        }
//        return value
//    }

}