package com.base.superfilemanager.activity


import android.animation.Animator
import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.hardware.camera2.CameraAccessException
import android.hardware.camera2.CameraManager
import android.location.LocationManager
import android.os.BatteryManager
import android.os.SystemClock
import android.provider.Settings
import android.view.View
import androidx.activity.OnBackPressedCallback
import androidx.activity.addCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.view.isVisible
import com.base.superfilemanager.R
import com.base.superfilemanager.databinding.ActivityBatteryInfoBinding
import com.base.superfilemanager.helps.BaseActivity
import com.base.superfilemanager.helps.ads.AdmobUtils
import com.base.superfilemanager.view.AFunOb
import java.util.Calendar
import java.util.Date
import kotlin.math.roundToInt

@SuppressLint("SetTextI18n")
class BatteryInfoActivity : BaseActivity<ActivityBatteryInfoBinding>() {
    override val isLightMode = true
    private lateinit var receiver: BatteryReceiver
    private lateinit var cm: CameraManager
    private lateinit var cameraId: String
    private var isTorchOn = false

    override val binding: ActivityBatteryInfoBinding by lazy {
        ActivityBatteryInfoBinding.inflate(layoutInflater)
    }

    override fun initView() {
        receiver = BatteryReceiver()
        val filter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
        registerReceiver(receiver, filter)

        cm = getSystemService(Context.CAMERA_SERVICE) as CameraManager
        try {
            cameraId = cm.cameraIdList[0]
        } catch (e: CameraAccessException) {
            e.printStackTrace()
        }

        setFilter()
        binding.idBatteryLottie.imageAssetsFolder = "dian_super_chi/images/"
        binding.idBatteryLottie.setAnimation("dian_super_chi/data.json")
        binding.idBatteryLottie.playAnimation()
        binding.root.postDelayed({
            playFinish()
        }, 5000)

        onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                AdmobUtils.showInterstitialAd(this@BatteryInfoActivity) {
                    finishToMain()
                }

            }
        })


        binding.switchTwo.setOnClickListener {
            turnOnBluetooth()
        }

        binding.switchThree.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                turnOnFlashLight()
            } else {
                turnOffFlashLight()
            }
        }

        binding.switchFour.setOnClickListener {
            jumpLocationSettings()
        }

        binding.btOk.setOnClickListener {
            binding.btOk.setBackgroundResource(R.drawable.bg_shape_set_click)
            startActivity(Intent(this, ResultActivity::class.java).apply {
                putExtra("from", AFunOb.BATTERY_INFO)
            })
            finish()
        }
        binding.ivBack.setOnClickListener {
            AdmobUtils.showInterstitialAd(this@BatteryInfoActivity) {
                finishToMain()
            }
        }
        onBackPressedDispatcher.addCallback {
            AdmobUtils.showInterstitialAd(this@BatteryInfoActivity) {
                finishToMain()
            }
        }

    }


    private val result1 =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
        }

    private val result2 =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {

        }

    private val settingResult =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {

        }

    private inner class BatteryReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            val current = intent?.extras?.getInt("level") ?: 0
            val total = intent?.extras?.getInt("scale") ?: 0
            val percent = current * 100 / total
            if (percent >= 30) {
                binding.imagePower.setImageResource(R.drawable.batteryl)
            } else {
                binding.imagePower.setImageResource(R.drawable.batteryh)
            }
            binding.tvLevel.text = "$percent%"
        }

    }


    private fun playFinish() {
        binding.idConsOne.isVisible = false
        binding.idConsBatteryFinish.isVisible = true
        binding.idBatteryFinish.addAnimatorListener(object : Animator.AnimatorListener {
            override fun onAnimationStart(p0: Animator) {

            }

            override fun onAnimationEnd(p0: Animator) {
                AdmobUtils.showInterstitialAd(this@BatteryInfoActivity) {
                    updateUI()
                }

            }

            override fun onAnimationCancel(p0: Animator) {

            }

            override fun onAnimationRepeat(p0: Animator) {

            }

        })
    }

    private fun checkFlashLight() {
        cm.registerTorchCallback(object : CameraManager.TorchCallback() {
            override fun onTorchModeChanged(cameraId: String, enabled: Boolean) {
                super.onTorchModeChanged(cameraId, enabled)
                if (cameraId == this@BatteryInfoActivity.cameraId) {
                    if (enabled && !isTorchOn) {
                        isTorchOn = true
                        binding.switchThree.isChecked = true
                    } else if (!enabled && isTorchOn) {
                        isTorchOn = false
                        binding.switchThree.isChecked = false
                    }
                }
            }
        }, null)
    }


    private fun turnOnFlashLight() {
        try {
            cm.setTorchMode(cameraId, true)
            // 打开手电筒
        } catch (e: CameraAccessException) {
            e.printStackTrace()
        }
    }

    private fun turnOffFlashLight() {
        try {
            cm.setTorchMode(cameraId, false)
            // 打开手电筒
        } catch (e: CameraAccessException) {
            e.printStackTrace()
        }
    }

    private fun jumpLocationSettings() {
        val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
        settingResult.launch(intent)
    }

    private fun checkLocation() {
        binding.switchFour.isChecked = isLocationEnabled(this)
    }

    private fun isLocationEnabled(context: Context): Boolean {
        val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
                locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
    }

    private fun setFilter() {
        val filter1 = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
        binding.tvVo.text = "${
            (registerReceiver(null, filter1)?.getIntExtra("voltage", 0)
                ?.toFloat()!!).roundToInt() / 1000.0
        }V"
        binding.tvTemp.text = "${
            (registerReceiver(null, filter1)?.getIntExtra("temperature", 0)
                ?.toFloat()!!).roundToInt() / 10.0
        }°C"

        val uptime = SystemClock.elapsedRealtime()
        val currantTime = Calendar.getInstance().time
        val batteryUseTime = currantTime.time - uptime
        val batteryDate = Date(batteryUseTime)
        binding.tvTime.text = "${batteryDate.hours} H ${batteryDate.minutes} M"


        val bm = getSystemService(Context.BATTERY_SERVICE) as BatteryManager
        val chargeCounter = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CHARGE_COUNTER)
        val pCapacity = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
        if (chargeCounter != Int.MIN_VALUE && pCapacity != Int.MIN_VALUE) {
            binding.tvMa.text = "${
                String.format("%.1f", (chargeCounter / (pCapacity.toFloat() / 100f)) / 1000f)
            } mAh"
        }

    }

    private fun updateUI() {
        binding.idBatteryLottie.visibility = View.GONE
        binding.idConsBatteryFinish.isVisible = false
        binding.llContent.isVisible = true
    }


    override fun onResume() {
        super.onResume()
        binding.btOk.setBackgroundResource(R.drawable.bg_shape_set)
        checkFlashLight()
        checkLocation()
    }

    fun turnOnBluetooth() {
        val intent2 = Intent(Settings.ACTION_BLUETOOTH_SETTINGS)
        result1.launch(intent2)
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(receiver);
    }
}