package com.zxhyis.tools.ui.`fun`


import android.Manifest
import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.hardware.camera2.CameraAccessException
import android.hardware.camera2.CameraManager
import android.location.LocationManager
import android.net.wifi.WifiConfiguration
import android.net.wifi.WifiManager
import android.os.BatteryManager
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.os.SystemClock
import android.provider.Settings
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import androidx.lifecycle.lifecycleScope
import com.applovin.mediation.ads.MaxInterstitialAd
import com.bumptech.glide.Glide
import com.zxhyis.tools.R
import com.zxhyis.tools.ad.preLoadInterAd
import com.zxhyis.tools.base.TopActivity
import com.zxhyis.tools.databinding.ActivityBatteryInfoBinding
import com.zxhyis.tools.logic.setOnClick
import com.zxhyis.tools.logic.setStatusBarTextDark
import com.zxhyis.tools.logic.startActivity
import com.zxhyis.tools.logic.testLog
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.Calendar
import java.util.Date
import java.util.Timer
import java.util.TimerTask
import kotlin.math.roundToInt

@SuppressLint("SetTextI18n")
class BatteryInfoActivity : TopActivity<ActivityBatteryInfoBinding>() {

    private lateinit var receiver: BatteryReceiver
    private var isNeedRefresh = true
    private var requestEnd = false
    private var maxAd: MaxInterstitialAd? = null
    private val handler = object : Handler(Looper.getMainLooper()) {

        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what) {
                1 -> {
                    if (i < 100) {
                        i += 1
                        vb.tvProgress.text = "$i%"
                    } else {
                        i = 100
                        vb.tvProgress.text = "$i%"
                        if (requestEnd){
                            timer.cancel()
                            if (maxAd!=null){
                                if (maxAd!!.isReady){
                                    maxAd?.showAd()
                                }else{
                                    lifecycleScope.launch {
                                        delay(500)
                                        updateUI()
                                    }
                                }
                            }else{
                                lifecycleScope.launch {
                                    delay(500)
                                    updateUI()
                                }
                            }
                        }else{
                            timer.cancel()
                            lifecycleScope.launch {
                                delay(500)
                                updateUI()
                            }
                        }
//                        timer.cancel()
//                        lifecycleScope.launch {
//                            delay(500)
//                            updateUI()
//                        }
                    }
                }
            }
        }
    }
    private lateinit var cm: CameraManager
    private lateinit var cameraId: String
    private var isTorchOn = false
    private val bluetoothAdapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter()
    private var isOpen = false

    @SuppressLint("MissingPermission")
    private val result =
        registerForActivityResult(ActivityResultContracts.RequestPermission()) {
            if (it) {
                isNeedRefresh = false
                vb.switchTwo.isChecked = true
                if (!isOpen) {
                    bluetoothAdapter?.disable()
                } else {
                    bluetoothAdapter?.enable()
                }
            }
        }

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

        }

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

        }


    private var i = 0
    private val timer = Timer()


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

    }


    override fun getViewBinding1(): ActivityBatteryInfoBinding {
        return ActivityBatteryInfoBinding.inflate(layoutInflater)
    }

    override fun init() {
        lifecycleScope.launch {
            delay(500)
            loadAd()
        }
        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()
        vb.inPower.tvTitle.text = "Battery information"
        vb.inPower.tvMenu.visibility = View.GONE
        vb.inPower.ivBack.setOnClick {
            finish()
        }

        vb.switchOne.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked) {
                checkHotspot(true)
            } else {
                checkHotspot(false)
            }
        }

        vb.switchTwo.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked) {
                turnOnBluetooth()
            } else {
                turnOffBluetooth()
            }
        }

        vb.switchThree.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked) {
                turnOnFlashLight()
            } else {
                turnOffFlashLight()
            }
        }

        vb.switchFour.setOnClick {
            jumpLocationSettings()
        }

        vb.btOk.setOnClick {
            vb.btOk.setBackgroundResource(R.drawable.bg_shape_set_click)
            startActivity<ResultActivity>("from" to "power")
        }

        setTimer()


        Glide.with(this)
            .asGif()
            .load(R.drawable.power_load)
            .into(vb.ivLoad)
    }

    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
                        vb.switchThree.isChecked = true
                    } else if (!enabled && isTorchOn) {
                        isTorchOn = false
                        vb.switchThree.isChecked = false
                    }
                }
            }
        }, null)
    }

    private fun checkHotspot(enabled: Boolean) {
        val wifiManager = getSystemService(Context.WIFI_SERVICE) as WifiManager
        try {
            if (enabled && wifiManager.isWifiEnabled) {
                wifiManager.isWifiEnabled = false
            }
            val setWifiApMethod = wifiManager.javaClass.getMethod(
                "setWifiApEnabled",
                WifiConfiguration::class.java,
                Boolean::class.javaPrimitiveType
            )
            setWifiApMethod.invoke(wifiManager, null, enabled)
        } catch (e: Exception) {
            testLog("Error setting WiFi AP state")
        }
    }

    private fun checkBluetooth() {
        vb.switchTwo.isChecked = bluetoothAdapter?.isEnabled == true
    }

    private fun turnOnBluetooth() {
        if (bluetoothAdapter != null && !bluetoothAdapter.isEnabled) {
            val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
            if (ActivityCompat.checkSelfPermission(
                    this,
                    Manifest.permission.BLUETOOTH_CONNECT
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                    result.launch(Manifest.permission.BLUETOOTH_CONNECT)
                    isOpen = true
                }
            } else {
                result1.launch(enableBtIntent)
            }
        }
    }

    private fun turnOffBluetooth() {
        if (bluetoothAdapter != null) {
            if (bluetoothAdapter.isEnabled) {
                if (ActivityCompat.checkSelfPermission(
                        this,
                        Manifest.permission.BLUETOOTH_CONNECT
                    ) != PackageManager.PERMISSION_GRANTED
                ) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                        result.launch(Manifest.permission.BLUETOOTH_CONNECT)
                        isOpen = false
                    }
                } else {
                    bluetoothAdapter.disable()
                }
            }
        }
    }

    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() {
        vb.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)
        vb.tvVo.text = "${
            (registerReceiver(null, filter1)?.getIntExtra("voltage", 0)
                ?.toFloat()!!).roundToInt() / 1000.0
        }V"
        vb.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)
        vb.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) {
            vb.tvMa.text = "${
                String.format(
                    "%.1f",
                    (chargeCounter / (pCapacity.toFloat() / 100f)) / 1000f
                )
            } mAh"
        }

    }

    private fun updateUI() {
        vb.apply {
            ivLoad.visibility = View.GONE
            tvProgress.visibility = View.GONE
            nsv.visibility = View.VISIBLE
            btOk.visibility = View.VISIBLE
            inPower.clInclude.visibility = View.VISIBLE
        }
    }

    private fun setTimer() {
        timer.schedule(
            object : TimerTask() {
                override fun run() {
                    val message = Message()
                    message.what = 1
                    handler.sendMessage(message)
                }
            },
            500,
            80
        )
    }

    override fun onResume() {
        super.onResume()
        vb.btOk.setBackgroundResource(R.drawable.bg_shape_set)
        setStatusBarTextDark(this)
        checkFlashLight()
        checkLocation()
        if (isNeedRefresh) {
            checkBluetooth()
        }
        testLog("123")
    }

    private fun loadAd() {
        preLoadInterAd(
            "f893f65dd2b1dff8",
            this, false, false, false,
            {
                if (it!=null){
                    maxAd=it
                }
                requestEnd = true
            }, {
                requestEnd = true
            }, {}, {}, {}, lifecycleScope
        )
    }

}