package com.zxhyis.toolss.ui.page


import android.animation.Animator
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.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.SystemClock
import android.provider.Settings
import android.view.View
import androidx.activity.OnBackPressedCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.view.isVisible
import com.zxhyis.toolss.R
import com.zxhyis.toolss.ad.AdmobUtils
import com.zxhyis.toolss.base.TopActivity
import com.zxhyis.toolss.databinding.ActivityBatteryInfoBinding
import com.zxhyis.toolss.logic.setOnClick
import com.zxhyis.toolss.logic.setStatusBarTextDark
import com.zxhyis.toolss.logic.startActivity
import com.zxhyis.toolss.logic.testLog
import com.zxhyis.toolss.ui.AFunOb
import com.zxhyis.toolss.ui.page.result.ResultActivity
import java.util.Calendar
import java.util.Date
import java.util.Timer
import kotlin.math.roundToInt

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

    private lateinit var receiver: BatteryReceiver
    private var isNeedRefresh = true

    //    private val handler = object : Handler(Looper.getMainLooper()) {
//
//        override fun handleMessage(msg: Message) {
//            super.handleMessage(msg)
//            when (msg.what) {
//                1 -> {
//                    if (i < 100) {
//                        i += 2
//                        vb.tvProgress.text = "$i%"
//                    } else {
//                        i = 100
//                        vb.tvProgress.text = "$i%"
//                        timer.cancel()
//                        lifecycleScope.launch {
//                            delay(500)
//                            AdmobUtils.showInterstitialAd(this@BatteryInfoActivity)
//                            //   MaxAdUtils.showMaxInterstitialAd(this@BatteryInfoActivity,"interstitial_slot")
//                            updateUI()
//                        }
//                    }
//                }
//            }
//        }
//    }
    private lateinit var cm: CameraManager
    private lateinit var cameraId: String
    private var isTorchOn = false
    private val bluetoothAdapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter()

//    @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 result2 =
        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() {
        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.idBatteryLottie.imageAssetsFolder = "battery_info/images/"
        vb.idBatteryLottie.setAnimation("battery_info/data.json")
        vb.idBatteryLottie.playAnimation()
        vb.root.postDelayed({
            playFinish()
        }, 5000)
        vb.inPower.tvTitle.text = "Battery information"
        vb.inPower.tvMenu.visibility = View.GONE
        vb.inPower.ivBack.setOnClick(javaClass.simpleName) {
            onBackPressedDispatcher.onBackPressed()
        }
        onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                AdmobUtils.showInterstitialAd(this@BatteryInfoActivity) {
                    finishToMain()
                }

            }
        })

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


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

        vb.switchFour.setOnClick(javaClass.simpleName) {
            jumpLocationSettings()
        }

        vb.btOk.setOnClick(javaClass.simpleName) {
            vb.btOk.setBackgroundResource(R.drawable.bg_shape_set_click)
            startActivity<ResultActivity>("from" to AFunOb.BATTERY_INFO)
            finish()
        }

        // setTimer()


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


    }

    private fun playFinish() {
        vb.idConsOne.isVisible = false
        vb.idConsBatteryFinish.isVisible = true
        vb.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
                        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{
//                    val intent2=Intent(Settings.ACTION_BLUETOOTH_SETTINGS)
//                    startActivity(intent2)
//                    isOpen = true
//                }
//            } else {
//                result1.launch(enableBtIntent)
//            }
//        }

        testLog("turnOnBluetooth")
        val intent2 = Intent(Settings.ACTION_BLUETOOTH_SETTINGS)
        result1.launch(intent2)
    }

    private fun turnOffBluetooth() {
        testLog("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()
//                }
//            }
//        }
        val intent2 = Intent(Settings.ACTION_BLUETOOTH_SETTINGS)
        result2.launch(intent2)
    }

    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
            idBatteryLottie.visibility = View.GONE
            idConsBatteryFinish.isVisible = false
            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()
//        }
    }


}