package com.base.scanqr.bean

import com.base.scanqr.bean.FunctionUIBean.Companion.KEY_WIFI
import com.base.scanqr.utils.LogEx
import com.base.scanqr.utils.QRCodeUtils.getPairKeyValue


data class WifiUIBean(
    var ssid: String = "",
    var bssid: String = "",
    var securityTypes: IntArray = intArrayOf(),
    var securityId: Int = 0
) : ScanBean(KEY_WIFI) {
    var password: String = ""
    var hidden: Boolean = false

    companion object{
        fun isWifiQR(qrCodeValue: String): Boolean {
            val flag = qrCodeValue.startsWith("WIFI:")
            if (flag) {
                return true
            }
            return false
        }

        fun createWifiQRString(bean: WifiUIBean): String {

            val content = StringBuilder()
            content.append("WIFI:")
            content.append("T:")
            if (bean.securityId == 0) {
                content.append("WPA/WPA2").append(";")
            }
            if (bean.securityId == 1) {
                content.append("WEP").append(";")
            }
            if (bean.securityId == 2) {
                content.append(";")
            }
            content.append("S:")
            content.append(bean.ssid).append(";")
            content.append("P:")
            content.append(bean.password).append(";")
            content.append("H:")
            content.append(bean.hidden).append(";")

            return  content.toString()
        }
        fun createWifiBean(qrCodeValue: String): WifiUIBean {
            val startTag = "WIFI:"
            val subString = qrCodeValue.subSequence(startTag.length, qrCodeValue.length)
            val splitList = subString.split(";")
            val wifiUIBean = WifiUIBean()


            val ssidKV = splitList.find { it.startsWith("S:") } ?: ""
            wifiUIBean.ssid = getPairKeyValue(ssidKV).second

            val passWordKV = splitList.find { it.startsWith("P:") } ?: ""
            wifiUIBean.password = getPairKeyValue(passWordKV).second

            val hiddenKV = splitList.find { it.startsWith("H:") } ?: ""
            wifiUIBean.hidden = getPairKeyValue(hiddenKV).second.toBoolean()

            val securityKy = splitList.find { it.startsWith("T") }
            if (securityKy.equals("WPA/WPA2")) {
                wifiUIBean.securityId = 0
            }
            if (securityKy.equals("WEP")) {
                wifiUIBean.securityId = 1
            }
            if (securityKy.equals("")) {
                wifiUIBean.securityId = 0
            }
            return wifiUIBean
        }
    }
}