package pxds.etmo

import android.animation.Animator
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.test.basd.supercleanermax.R
import com.test.basd.supercleanermax.databinding.WendkvBinding
import pxds.dlpf.buoz.fico.Dsce
import pxds.lmmd.zmwf.Bpfw
import pxds.lmmd.zmwf.Khko.setTrackedOnClickListener
import pxds.lmmd.zmwf.Khko.string
import pxds.lmmd.zmwf.jyyf.hwbn.wzxb.Utdc
import java.util.Calendar
import java.util.Date
import kotlin.math.roundToInt

class Jmut : Bpfw<WendkvBinding>() {

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

    private lateinit var cameraId: String

    private lateinit var cm: CameraManager

    private var isTorchOn = false

    private lateinit var receiver: BatteryReceiver

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

        }

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

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

        }

    override val isLightMode = true

    private fun turnOffFlashLight() {
        try {
            cm.setTorchMode(cameraId, false)

        } catch (e: CameraAccessException) {
            e.printStackTrace()
        }
    }

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

    private fun setFilter() {
        val filter1 = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
        binding.iiazwne.text = "${
            (registerReceiver(null, filter1)?.getIntExtra(R.string.ޑލޚޏގ_D.string(), 0)
                ?.toFloat()!!).roundToInt() / 1000.0
        }V"
        binding.tejptzy.text = "${
            (registerReceiver(null, filter1)?.getIntExtra(R.string.ޖބތޠޥ_D.string(), 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.smokwld.text = R.string.ޠޔވޑޜ_D.string((batteryDate.hours).toString(), (batteryDate.minutes).toString())

        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.zyziqla.text = "${
                String.format(R.string.ޟހޡސޜ_D.string(), (chargeCounter / (pCapacity.toFloat() / 100f)) / 1000f)
            } mAh"
        }

    }

    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 turnOnFlashLight() {
        try {
            cm.setTorchMode(cameraId, true)

        } catch (e: CameraAccessException) {
            e.printStackTrace()
        }
    }

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

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

    private inner class BatteryReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            val current = intent?.extras?.getInt(R.string.ޥޝގޥށ_D.string()) ?: 0
            val total = intent?.extras?.getInt(R.string.ޚގތހޢ_D.string()) ?: 0
            val percent = current * 100 / total
            if (percent >= 30) {
                binding.pkpivtn.setImageResource(R.mipmap.tunzonid)
            } else {
                binding.pkpivtn.setImageResource(R.mipmap.yzemtaut)
            }
            binding.scbcfec.text = R.string.ޓޏރޤޢ_D.string((percent).toString())
        }

    }

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

    override fun onResume() {
        super.onResume()
        binding.qzpyxwf.setBackgroundResource(R.drawable.sbxnekxx)
        checkFlashLight()
        checkLocation()
    }

    private fun updateUI() {
        binding.intgxcn.visibility = View.GONE
        binding.ddbdvwq.isVisible = false
        binding.ziihecw.isVisible = true
    }

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

    private fun playFinish() {
        binding.lxmeemw.isVisible = false
        binding.ddbdvwq.isVisible = true
        binding.kbovjzl.addAnimatorListener(object : Animator.AnimatorListener {
            override fun onAnimationStart(p0: Animator) {

            }

            override fun onAnimationEnd(p0: Animator) {
                Utdc.showInterstitialAd(this@Jmut) {
                    updateUI()
                }

            }

            override fun onAnimationCancel(p0: Animator) {

            }

            override fun onAnimationRepeat(p0: Animator) {

            }

        })
    }

    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.intgxcn.imageAssetsFolder = R.string.ރޜޝހނ_D.string()
        binding.intgxcn.setAnimation(R.string.ޝޛޣވޤ_D.string())
        binding.intgxcn.playAnimation()
        binding.root.postDelayed({
            playFinish()
        }, 5000)

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

            }
        })

        binding.rtmnacj.setTrackedOnClickListener {
            turnOnBluetooth()
        }

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

        binding.rtvyruh.setTrackedOnClickListener {
            jumpLocationSettings()
        }

        binding.qzpyxwf.setTrackedOnClickListener {
            Utdc.showInterstitialAd(this) {
                startActivity(Intent(this, Iqnb::class.java).apply {
                    putExtra(R.string.ޣޟމޅކ_D.string(), Dsce.BATTERY_INFO)
                })
                finish()
            }
        }
        binding.kgxhrze.setTrackedOnClickListener {
            Utdc.showInterstitialAd(this@Jmut) {
                finishToMain()
            }
        }
        onBackPressedDispatcher.addCallback {
            Utdc.showInterstitialAd(this@Jmut) {
                finishToMain()
            }
        }

    }
}