package com.base.scanqr.ui.wifi

import android.Manifest
import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.wifi.WifiConfiguration
import android.net.wifi.WifiManager
import android.os.Build
import android.text.Editable
import android.text.TextWatcher
import androidx.activity.addCallback
import androidx.core.view.updatePadding
import com.base.scanqr.R
import com.base.scanqr.ads.AdsMgr
import com.base.scanqr.ads.AdsShowCallBack
import com.base.scanqr.base.BaseActivity
import com.base.scanqr.bean.WifiUIBean
import com.base.scanqr.databinding.ActivityWifiBinding
import com.base.scanqr.ui.widget.WifiSelectDialog.showWifiSelectDialog
import com.base.scanqr.utils.BarUtils
import com.base.scanqr.utils.LogEx
import com.base.scanqr.utils.PermissionUtils.checkLocationPermission
import com.base.scanqr.utils.ToastUtils.toast
import com.google.gson.Gson
import com.gyf.immersionbar.ktx.immersionBar

/**
 * 获取不到的原因,手机定位没有打开233
 */
class WifiActivity : BaseActivity<ActivityWifiBinding>(ActivityWifiBinding::inflate) {

    private var wifiManager: WifiManager? = null
    private var wifiScanReceiver: WifiScanReceiver? = null
    private var wifiList = arrayListOf<WifiUIBean>()
    private var wifiScanFinish: Boolean = false
    private var currentWifi: WifiUIBean = WifiUIBean()

    override fun onResumeOneShoot() {
        super.onResumeOneShoot()
        val flag = changeLanguage()
        if (flag) return
    }

    override fun initView() {
        super.initView()
        binding.clTop.updatePadding(top = BarUtils.getStatusBarHeight())
        AdsMgr.showNative(binding.flAd, R.layout.layout_admob_app_exit)
    }

    override fun initListener() {
        super.initListener()
        onBackPressedDispatcher.addCallback {
            AdsMgr.showInsert(this@WifiActivity, false, object : AdsShowCallBack() {
                override fun close(where: Int) {
                    finishToMainTop()
                }

                override fun failed(where: Int) {
                    finishToMainTop()

                }

                override fun googleFailed(where: Int) {
                    finishToMainTop()
                }
            })
        }
        binding.flBack.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        binding.flWifi.setOnClickListener {
            if (!checkLocationPermission()) {
                toast("need permission", true)
                return@setOnClickListener
            }

            if (!wifiScanFinish) {
                toast("wifi is scanning", true)
                return@setOnClickListener
            }

            showWifiSelectDialog(wifiList) { wifi ->
                binding.editSSID.setText(wifi.ssid)
                currentWifi = wifi
                binding.rg.check(R.id.radioButton1)
            }
        }
        binding.rg.setOnCheckedChangeListener { group, checkedId ->
            when (checkedId) {
                R.id.radioButton1 -> {
                    currentWifi.securityId = 0
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                        currentWifi.securityTypes = intArrayOf(WifiConfiguration.SECURITY_TYPE_PSK)
                    }
                }

                R.id.radioButton2 -> {
                    currentWifi.securityId = 1
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                        currentWifi.securityTypes = intArrayOf(WifiConfiguration.SECURITY_TYPE_WEP)
                    }
                }

                R.id.radioButton3 -> {
                    currentWifi.securityId = 2
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                        currentWifi.securityTypes = intArrayOf(WifiConfiguration.SECURITY_TYPE_OPEN)
                    }
                }
            }
        }
        binding.rg.check(R.id.radioButton1)
        binding.editSSID.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                currentWifi.ssid = s.toString()
            }
        })
        binding.editPassword.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                currentWifi.password = s.toString()
            }
        })
        binding.flQueren.setOnClickListener {
            if (currentWifi.ssid.isEmpty()) {
                toast("Enter wifi ssid", true)
                return@setOnClickListener
            }
            if (currentWifi.password.isEmpty()) {
                toast("Enter password wifi", true)
                return@setOnClickListener
            }

            startActivity(Intent(this@WifiActivity, WifiCodeActivity::class.java).apply {
                putExtra("data", Gson().toJson(currentWifi))
            })
            finish()
        }
        binding.switchHidden.setOnCheckedChangeListener { buttonView, isChecked ->
            currentWifi.hidden = isChecked
        }

        wifiManager = getSystemService(Context.WIFI_SERVICE) as WifiManager?

        registerWifiReceiver()

        if (!checkLocationPermission()) {
            launcher.launch(
                arrayOf(
                    Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_WIFI_STATE
                )
            ) {
                val success = wifiManager?.startScan()
                LogEx.logDebug(TAG, "success=$success")
            }
        } else {
            val success = wifiManager?.startScan()
            LogEx.logDebug(TAG, "success=$success")
        }

    }

    override fun configSystemBar() {
        immersionBar {
            statusBarColor("#FFFFFFFF")
            statusBarDarkFont(true)
        }
    }

    /**
     * {"android. permission. ACCESS_WIFI_STATE","android. permission. ACCESS_FINE_LOCATION"}
     */
    inner class WifiScanReceiver : BroadcastReceiver() {
        @SuppressLint("MissingPermission")
        override fun onReceive(context: Context?, intent: Intent?) {
            LogEx.logDebug(TAG, "onReceive")
            if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION == intent?.action) {
                wifiManager?.scanResults?.forEach { result ->
                    val wifiUIBean = WifiUIBean()
                    wifiUIBean.ssid = result.SSID
                    wifiUIBean.bssid = result.BSSID
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                        wifiUIBean.securityTypes = result.securityTypes
                    }
//                    LogEx.logDebug(TAG, "SSID=${result.SSID} ")
//                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
//                        WifiConfiguration.SECURITY_TYPE_PSK //wpa/wpa2
//                        WifiConfiguration.SECURITY_TYPE_WEP//wep
//                        WifiConfiguration.SECURITY_TYPE_OPEN//no
//                        LogEx.logDebug(TAG, "securityTypes=${result.securityTypes} ")
//                    }
//                    LogEx.logDebug(TAG, "SSID=${result.BSSID} ")
                    if (wifiUIBean.ssid.isNotEmpty()) {
                        wifiList.add(wifiUIBean)
                    }
                }
                wifiScanFinish = true
                binding.tvWifiNumber.text = wifiList.size.toString()
            }
        }
    }

    private fun registerWifiReceiver() {
        val intentFilter = IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)
        wifiScanReceiver = WifiScanReceiver()
        registerReceiver(wifiScanReceiver, intentFilter)
    }

    private fun unWifiRegisterReceiver() {
        unregisterReceiver(wifiScanReceiver)
    }

    override fun onDestroy() {
        super.onDestroy()
        unWifiRegisterReceiver()
    }
}