package com.rdiot.yx485.device.view

import android.content.Context
import android.content.Intent
import android.net.wifi.WifiInfo
import android.net.wifi.WifiManager
import android.os.Bundle
import android.provider.Settings
import android.text.TextUtils
import android.view.View
import com.lindroy.iosdialog.IAlertDialog
import com.rdiot.yx485.BaseActivity
import com.rdiot.yx485.R
import com.rdiot.yx485.databinding.ActivityOnlineBinding
import com.rdiot.yx485.util.PermissionUtils
import com.zcolin.frame.util.LogUtil


/**
 * 输入WiFi信息页
 * @author mR2hao
 * @date 2022/11/21
 */
class EnterWifiInfoActivity : BaseActivity() {

    private lateinit var mBinding: ActivityOnlineBinding
    private lateinit var wifiInfo: WifiInfo
    var wifiSsid: String = ""

    companion object {
        fun newIntent(context: Context, bundle: Bundle) {
            Intent(context, EnterWifiInfoActivity::class.java).apply {
                putExtra("bundle", bundle)
                context.startActivity(this)
            }
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = ActivityOnlineBinding.inflate(layoutInflater)
        setContentView(mBinding.root)
        initView();
    }


    private fun initView() {
        mBinding.layoutTitle.btnTitleLeft.setOnClickListener { finish() }
        mBinding.tvChangeWifi.setOnClickListener {
            goToSystemWifiSetting(true)
        }

        mBinding.btnNext.setOnClickListener {
            gotoScanDevice()
        }

    }

    private fun gotoScanDevice() {
        if (TextUtils.isEmpty(wifiSsid)) {
            showMessage("wifi ssid为空")
            return
        }

        val pwd = mBinding.editPwd.text.toString()
        if (TextUtils.isEmpty(pwd)) {
            showMessage("请输入wifi密码")
            return
        }

        val bundle = intent.getBundleExtra("bundle") ?: Bundle()
        bundle.putString("ssid", wifiSsid)
        bundle.putString("pwd", pwd)
        if (PermissionUtils.checkPermissionGranted(this, "ble")) {
            ScanDeviceActivity.newIntent(this, bundle)
        }
    }

    override fun onResume() {
        super.onResume()

        wifiInfo =
            (applicationContext.getSystemService(WIFI_SERVICE) as WifiManager).connectionInfo
        getWifiInfo()
    }

    /** 检查Wi-Fi信息是否正确 */
    private fun checkWifiInfoIsOk(): Boolean {
        if (getSSID().contains("unknown ssid", true)) {
            // 没有连接到WI-FI
            LogUtil.e("EnterWifiInfoAcitivy", "没有连接到 Wifi")
            IAlertDialog.build(this)
                .setTitle(R.string.hint)
                .setMessage(R.string.not_connect_wifi)
                .setCancelOutside(false)
                .setNegButtonText(R.string.got_it)
                .setNegClickListener { dialogInterface ->
                    dialogInterface.dismiss()
                }
                .setDismissible(false)
                .setAlpha(1.0F)
                .setPosButtonText(R.string.go_setting)
                .setPosClickListener { dialogInterface ->
                    goToSystemWifiSetting(true)
                    dialogInterface.dismiss()
                }.show()
            return false
        }

        return true
    }


    /**
     * 检查当前连接的网络是否为5G WI-FI
     */
    private fun is5GWifiConnected() = wifiInfo.frequency in 4900..5900

    /** 获取WI-FI信息 */
    private fun getWifiInfo() {

        if (checkWifiInfoIsOk()) {
            val curSsid = getSSID()
            wifiSsid = curSsid
            mBinding.etWifi.text = wifiSsid

            if (is5GWifiConnected()) {
                mBinding.tv5gErr.visibility = View.VISIBLE
            } else {
                mBinding.tv5gErr.visibility = View.INVISIBLE
            }
        }
    }


    /**
     * 获取当前连接WIFI的SSID
     */
    private fun getSSID(): String {
        val len: Int = wifiInfo.ssid.length
        return if (wifiInfo.ssid.startsWith("\"") && wifiInfo.ssid.endsWith("\"")) {
            wifiInfo.ssid.substring(1, len - 1)
        } else {
            wifiInfo.ssid
        }
    }


    /**
     * 打开Wi-Fi设置页面
     * @param justGo 直接跳转
     * @return [Intent] 意图
     */
    private fun goToSystemWifiSetting(justGo: Boolean): Intent {
        val intent = Intent(Settings.ACTION_WIFI_SETTINGS)
        intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
        if (justGo) startActivity(intent)
        return intent
    }


}
