
var _userdata = require("userdata.js");
var userData = _userdata.userData;
const fs = require("@system.fs")
var factoryDivPageJump = require("factoryDivPageJump.js");

var systemCtrl = require("systemCtrl.js");
// var systemCtrl = require("systemCtrl.js");
var resultsWifiList = undefined;
var that;

var wlan_enalbed = userData.enableWLANSwitchFlag
// const generalSettingPage = proxy.indexObj.getPage("installationGeneralSetting");

var wifi_div = undefined;
var wifi_list_div = undefined;
// this.proxy = proxy;
// this.pageObj = proxy.indexObj;
// var that = this;

// var resultsWifiList = null;
var cnt = 0;
var connectWifiSSID = null;
var connectWifiPassword = null;
var signalLevel = 0;
var _encryptedMode = "";

var _connectWifiTimerId = undefined
var _connectWifiCnt = 0;

var connectingWifiTimer = false;
var connectingState = 0; //模拟用来表示连接wifi的状态，0表示未连接，1表示已连接
var connectTimeout = 0;

var flushTimeTimer = null;
var oneFlag = 1;
var writeWpaConf = require("writeWpaConf.js")


// var wlan_enalbed = userData.enableWLANSwitchFlag
// const generalSettingPage = proxy.indexObj.getPage("generalSetting");

// var wifi_div = undefined;
// var wifi_list_div = undefined;

function testWifiInitPage(obj) {
    that = obj;
}

// function parseWifiScanResults(output) {
//     const lines = output.split('\n');
//     const results = [];

//     // 从第三行开始解析（跳过前两行标题）
//     for (let i = 2; i < lines.length; i++) {
//         const line = lines[i].trim();
//         if (!line) continue; // 跳过空行

//         // 按多个空格分割行
//         const parts = line.split(/\s+/).filter(part => part !== '');

//         if (parts.length >= 4) {
//             const signalLevel = parseInt(parts[2]); // 信号强度在第3列
//             let ssid = parts.slice(4).join(' '); // SSID 在第5列及之后（可能包含空格）
//             const flags = parts[3]; // 加密标志在第4列
//             const isEncrypted = !flags.includes("[ESS]") ||
//                 flags.includes("WPA") ||
//                 flags.includes("WEP") ||
//                 flags.includes("PSK");
//             results.push({
//                 ssid: ssid || '', // 如果 SSID 为空，则设为空字符串
//                 signalLevel: signalLevel,
//                 isEncrypted: isEncrypted
//             });
//         }
//     }

//     return results;
// }
function parseWifiScanResults(output) {
    const lines = output.split('\n');
    const results = [];

    // 从第三行开始解析（跳过前两行标题）
    for (let i = 2; i < lines.length; i++) {
        const line = lines[i].trim();
        if (!line) continue; // 跳过空行

        // 按多个空格分割行
        const parts = line.split(/\s+/).filter(part => part !== '');

        if (parts.length >= 4) {
            const signalLevel = parseInt(parts[2]); // 信号强度在第3列
            let ssid = parts.slice(4).join(' '); // SSID 在第5列及之后（可能包含空格）
            const flags = parts[3]; // 加密标志在第4列
            const isEncrypted = !flags.includes("[ESS]") ||
                flags.includes("WPA") ||
                flags.includes("WEP") ||
                flags.includes("PSK");

            let encryptedMode = 'Open'; // 默认开放网络
            if (flags.includes('WPA3')) {
                encryptedMode = 'WPA';
            } else if (flags.includes('WPA2')) {
                encryptedMode = 'WPA';
            } else if (flags.includes('WPA')) {
                encryptedMode = 'WPA';
            } else if (flags.includes('WEP')) {
                encryptedMode = 'WEP';
            } else if (!flags.includes('[ESS]')) {
                encryptedMode = 'Unknown'; // 非开放网络但未识别类型
            }
            //  console.debug("ssid:" + ssid + " signalLevel:" + signalLevel + " isEncrypted:" + isEncrypted + " encryptedMode:" + encryptedMode);
            results.push({
                ssid: ssid || '', // 如果 SSID 为空，则设为空字符串
                signalLevel: signalLevel,
                isEncrypted: isEncrypted,
                encryptedMode: encryptedMode
            });
        }
    }

    return results;
}

// var wlan_enalbed = userData.enableWLANSwitchFlag
// // const generalSettingPage = proxy.indexObj.getPage("generalSetting");

// var wifi_div = undefined;
// var wifi_list_div = undefined;
// this.proxy = proxy;
// this.pageObj = proxy.indexObj.getPage("generalSetting");
// var that = this;



// proxy.on("onEnableWLANSwitch", function () {


function onGotoWlanEnterPasswordPageEvent(value, signal, encrypted) {
    console.log("receive onGotoWlanEnterPasswordPage singal!");
    // var activePage = that.activePage;
    that.crtTitleWlanEnterPasswordText = value; //刷新标题
    that.crtTitleWlanConnectingText = value;
    connectWifiSSID = value;
    signalLevel = signal;
    _encryptedMode = encrypted;
    console.log("==========signalLevel :" + signalLevel + "connectWifiSSID :" + connectWifiSSID + "=======");
    that.crtEnterPasswordShowText = "";
    that.crtEnterPasswordShowInvisiableText = "";
    that.output = ""; //每次从外面进入页面时，还原已经输入的字符
    that.invisiableOutput = "";

    factoryDivPageJump.movePage("id_wlanEnterPasswordPage");
}


// function connect_wifi(ssid, psk) {
function connect_wifi(ssid, psk, mode) {
    console.log("===============connect_wifi: " + ssid + "===psk: " + psk + "===mode: " + mode);
    writeWpaConf.set(ssid, psk, mode)
    systemCtrl.executeSystemCommand("/tmp/wlanInit.sh &") //重启wifi连接
    return

    // if (psk == "Open") {
    systemCtrl.executeSystemCommand("killall -9 udhcpc")
    systemCtrl.executeSystemCommand("wpa_cli -p /tmp/wpa_supplicant/sockets -i wlan0 set_network 0 ssid \'\"" + ssid + "\"\'")
    systemCtrl.executeSystemCommand("usleep 10000") //10ms 用于缓冲
    systemCtrl.executeSystemCommand("wpa_cli -p /tmp/wpa_supplicant/sockets -i wlan0 set_network 0 psk \'\"" + psk + "\"\'")
    systemCtrl.executeSystemCommand("usleep 10000") //10ms 用于缓冲
    systemCtrl.executeSystemCommand("wpa_cli -p /tmp/wpa_supplicant/sockets -i wlan0 save_config")
    systemCtrl.executeSystemCommand("usleep 10000") //10ms 用于缓冲
    systemCtrl.executeSystemCommand("wpa_cli -p /tmp/wpa_supplicant/sockets -i wlan0 reconfigure")
    //启动wpa_supplicant进程
    systemCtrl.executeSystemCommand("usleep 200000") //200ms 用于缓冲设置和执行
    systemCtrl.executeSystemCommand("wpa_cli -p /tmp/wpa_supplicant/sockets -i wlan0 disable_network 0")
    systemCtrl.executeSystemCommand("usleep 10000") //10ms 用于缓冲
    systemCtrl.executeSystemCommand("wpa_cli -p /tmp/wpa_supplicant/sockets -i wlan0 enable_network 0")
    systemCtrl.executeSystemCommand("usleep 500000") //500ms 用于缓冲联网状态
    //启动udhcpc
    systemCtrl.executeSystemCommand("udhcpc -b -i wlan0 -t 1 -A 1 -R -H test")
    // }
    // else if(!(psk == null || psk == "" || psk == "null")) {

    // }
    // else {
    console.log("ssid: " + ssid + "psk " + psk + "mode " + mode);
    //     writeWpaConf.set(ssid, psk, mode)
    //     systemCtrl.executeSystemCommand("/tmp/wlanInit.sh &") //重启wifi连接
    //     // return
    // }
}
function diConnectWifi() {
    systemCtrl.executeSystemCommand("wpa_cli -p /tmp/wpa_supplicant/sockets -i wlan0 disable_network 0")
    systemCtrl.executeSystemCommand("usleep 10000") // 10ms 用于缓冲
    systemCtrl.executeSystemCommand("wpa_cli -p /tmp/wpa_supplicant/sockets -i wlan0 remove_network 0")
    systemCtrl.executeSystemCommand("usleep 10000") // 10ms 用于缓冲
    systemCtrl.executeSystemCommand("wpa_cli -p /tmp/wpa_supplicant/sockets -i wlan0 save_config")
    systemCtrl.executeSystemCommand("usleep 10000") // 10ms 用于缓冲
    systemCtrl.executeSystemCommand("wpa_cli -p /tmp/wpa_supplicant/sockets -i wlan0 reconfigure")
    systemCtrl.executeSystemCommand("usleep 200000") // 200ms 用于缓冲设置和执行
    systemCtrl.executeSystemCommand("killall -9 udhcpc") // 停止 udhcpc
}
function WifiNoActive() {

    console.log("=====WifiNoActive=====");

    userData.wlanSsid = null;
    userData.wlanSignalLevel = 0;
    userData.wlanPassword = null;

    that.$setY("id_enableWLANListArea0", -800);
    that.$setY("wifiListItem", 0);
    that.$setY("id_wifiListItem_Text", -800);
    that.$setY("id_wifiListItem_xLine", -800);


    systemCtrl.executeSystemCommand("ifconfig wlan0 down")
}
function scanRefreshWifiList(wifi_list) {
    var enableWLANListItemSearchDiv = document.getElementById('id_enableWLANListItemSearchDiv')


    if (!enableWLANListItemSearchDiv)
        return

    if (!wifi_div) {
        wifi_div = document.createElement('div', {
            top: 0,
            left: 0,
            width: 420,
        }, enableWLANListItemSearchDiv)
    }
    console.log("=====refreshWifiListlog=====1");
    // if (wifi_list_div) {
    //     wifi_div.removeChild(wifi_list_div)
    // }

    wifi_list_div = document.createElement('div', {
        top: 0,
        left: 0,
        width: 420,
        "background-color": "#000000",
    }, wifi_div)
    console.log("=====refreshWifiListlog=====2");
    var top = 0;
    for (var i = 0; i < wifi_list.length; i++) {
        // if (wifi_list[i].ssid == userData.wlanSsid) {
        //     continue;
        // }
        var ssid = wifi_list[i].ssid
        var signalLevel = wifi_list[i].signalLevel
        var isEncrypted = wifi_list[i].isEncrypted
        var encryptedMode = wifi_list[i].encryptedMode
        console.log("========ssid:" + ssid + " signalLevel:" + signalLevel + " isEncrypted:" + isEncrypted + " encryptedMode:" + encryptedMode + "=====")

        if (ssid.length == 0)
            continue
        var process = require("@system.process");
        if (process.platform == "win32") {

            if (signalLevel > -50) {
                var src = './../re860a-v1.0/images/main/wifiSignalLevel3.png'
            } else if (signalLevel <= -50 && signalLevel > -70) {
                var src = './../re860a-v1.0/images/main/wifiSignalLevel2.png'
            } else {
                var src = './../re860a-v1.0/images/main/wifiSignalLevel1.png'
            }
        }
        else {

            if (signalLevel > -50) {
                var src = './../RE860A/images/main/wifiSignalLevel3.png'
            } else if (signalLevel <= -50 && signalLevel > -70) {
                var src = './../RE860A/images/main/wifiSignalLevel2.png'
            } else {
                var src = './../RE860A/images/main/wifiSignalLevel1.png'
            }
        }

        var chooseAreaDiv = document.createElement('div', {
            top: top,
            left: 20,
            width: 460,
            height: 66,
        }, wifi_list_div)


        document.createElement('text', {
            top: 14,
            left: 50,
            width: 420,
            height: 50,
            "text-align": "left",
            "font-size": 22,
            "color": "white",
            'text-overflow': "ellipsis",
            "background-color": "transparent",
            "text": ssid + "(" + signalLevel + " dBm)",
            "ssid": ssid,
            "encryptedMode": encryptedMode,
            "signalValue": signalLevel,
            "events": {
                onclick: function (node, topNode, x, y) {
                    // node.attributes.text = "selected";
                    // systemCtrl.executeSystemCommand("/mnt/app/quicknode/shell/eAplay.sh /mnt/app/voice_click.wav");
                    console.log("node.attributes.text = " + this.attributes.text + " node.attributes.signalValue = " + this.attributes.signalValue);
                    console.log("click wlan_list_item"); //需要添加一个点击事件
                    console.log("this.attributes.ssid = " + this.attributes.ssid);
                    onGotoWlanEnterPasswordPageEvent(this.attributes.ssid, this.attributes.signalValue, this.attributes.encryptedMode);
                    // proxy.emit("onGotoWlanEnterPasswordPage", this.attributes.text, this.attributes.signalValue);
                }
            }
        }, chooseAreaDiv)

        document.createElement('div', {
            top: 65,
            left: 8,
            width: 464,
            height: 1,
            opactity: 1,
            "background-color": "#999999",
        }, chooseAreaDiv)

        // if (isEncrypted) {
        //     document.createElement('img', {
        //         top: 20,
        //         left: 363,
        //         width: 21,
        //         height: 26,
        //         src: "./images/settings/connecteWlanLockedPng.png",
        //     }, chooseAreaDiv)
        // }

        document.createElement('img', {
            top: 14,
            left: 8,
            width: 38,
            height: 38,
            src: src,
        }, chooseAreaDiv)

        top += 70
    }

    wifi_list_div.setAttribute('height', top)
    wifi_div.setAttribute('height', top)
    console.log("top=", top)
    // that.$setHeight("id_enableWLANListItemTemplate",top);
}


function enableWLANSwitch() {

    console.log("Is @@@@@@@@@@@@@@@@@@@@@@@@@@#3333333")
    // if (!userData.enableWLANSwitchFlag) {
    //     return;
    // }
    var process = require("@system.process")
    if (process.platform == "win32") {
        console.log("its win32.")
        return;
    }
    console.log("resultsWifiList:")
    if (resultsWifiList && oneFlag) {
        scanRefreshWifiList(resultsWifiList)
        oneFlag = 0;
    }

    systemCtrl.executeSystemCommand("rm -fr /tmp/scan_result.txt")
    systemCtrl.executeSystemCommand("wpa_cli -p /tmp/wpa_supplicant/sockets scan")
    setTimeout(function () {

        systemCtrl.executeSystemCommand("wpa_cli -p /tmp/wpa_supplicant/sockets scan_results > /tmp/scan_result.txt")
        var content = fs.read("/tmp/scan_result.txt", "r")
        console.log("====================content")
        if (content) {
            var listScanValue = parseWifiScanResults(content)
            if (listScanValue.length > 0) {
                resultsWifiList = listScanValue;
                console.log(JSON.stringify(resultsWifiList))
                scanRefreshWifiList(resultsWifiList)
            }
        }
    }, 5000)

}




function getWifiInfo(ssid) {
    console.log("getWifiInfo called with SSID: " + ssid);
    if (!resultsWifiList) {
        console.log("resultsWifiList is not available.");
        return null; // 如果 resultsWifiList 为空，则返回 null
    }
    // console.log("!!GET resultsWifiList: " + resultsWifiList);
    // 遍历 resultsWifiList 查找指定 SSID
    let foundWifi = null;
    for (let i = 0; i < resultsWifiList.length; i++) {
        if (resultsWifiList[i].ssid === ssid) {
            console.log("Found SSID: " + ssid);
            foundWifi = resultsWifiList[i];
            break;
        }
    }

    if (!foundWifi) {
        console.log("SSID not found: " + ssid);
        return {
            ssid: ssid,
            signalLevel: null, // 信号强度为空
            isEncrypted: null, // 加密状态为空
            isConnected: false // 未连接
        };
    } else {
        console.log("Found WiFi: " + JSON.stringify(foundWifi));
    }

    // 检查当前 WiFi 状态
    let isConnected = false;
    if (userData.wlanSsid === ssid && userData.enableWLANSwitchFlag === 1) {
        isConnected = true;
    } else {
        // 通过系统命令检查当前 WiFi 状态
        systemCtrl.executeSystemCommand("wpa_cli -p /tmp/wpa_supplicant/sockets -i wlan0 status > /tmp/wifi_status.txt");
        const statusContent = fs.read("/tmp/wifi_status.txt", "r");
        if (statusContent) {
            const statusLines = statusContent.split('\n');
            for (let i = 0; i < statusLines.length; i++) {
                const line = statusLines[i].trim();
                if (line.startsWith("wpa_state=")) {
                    const state = line.split('=')[1];
                    if (state === "COMPLETED") {
                        isConnected = true;
                        break;
                    }
                }
            }
        }
    }

    return {
        ssid: ssid,
        signalLevel: foundWifi.signalLevel, // 信号强度
        isEncrypted: foundWifi.isEncrypted, // 是否加密
        isConnected: isConnected // 是否已连接
    };
}


function onInstallationGeneralSettingConnectWifi(value) {
    console.log("receive onInstallationGeneralSettingConnectWifi singal!");

    console.log("Send cmd to connect wifi,connecting...");

    if (value != undefined) {
        connectWifiPassword = value;
    }
    var cmdStr = "02|0A|0A|";
    var ssidCode = connectWifiPassword;
    // var ssidCode = "HUAWEIK50S";
    var ssidBytes = Array.from(ssidCode, char => char.charCodeAt(0));
    var ssidHexString = ssidBytes.map(byte => byte.toString(16).padStart(2, '0')).join('|');
    cmdStr += ssidHexString + "|";
    var passWordCode = connectWifiSSID;
    // var passWordCode = "Ww88888888";
    var passWordBytes = Array.from(passWordCode, char => char.charCodeAt(0));
    var passWordHexString = passWordBytes.map(byte => byte.toString(16).padStart(2, '0')).join('|');
    cmdStr += passWordHexString + "|";
    console.log("aaaaaaaaaaaaaaaaaaaaaaaa==================")

    var msdk6ACmdArr = cloudComSerial.serialMsdkCmdArrayPack(0x6A, cmdStr);
    cloudComSerial.sendCmd(msdk6ACmdArr);

    if (connectingWifiTimer) {
        clearInterval(connectingWifiTimer);
    }
    connectTimeout = 0;

    connectingWifiTimer = setInterval(function () {
        var dotContext = ["", ".", "..", "..."];

        //  console.debug("================test=============")

        if (connectingState == 0) {
            connectTimeout++;
        } else {
            connectTimeout = 0;
            console.log("wifi connect success!");

            setAreaButtonDivOn();

            userData.wlanSsid = connectWifiSSID;
            userData.wlanPassword = passWordCode;
            WifiActive();

            var activePage = that.pageObj.activePage;
            handleJumpPage.moveShowHidePage(that.pageObj, activePage, "SuccessConnectWifi");

            clearInterval(connectingWifiTimer);
        }

        if (connectTimeout > 60) {
            console.log("wifi connect timeout!");

            setAreaButtonDivOn();
            WifiNoActive();

            // handleJumpPage.moveShowHidePage(that.pageObj, activePage, "failConnectWifi");

            clearInterval(connectingWifiTimer);
        }

    }, 1000);

    //使用wpa模式去连wifi
    connectWifiByWpa(connectWifiSSID, connectWifiPassword, function (result) {
        if (result == 0) {
            console.log("Connect wifi success");
            setTimeout(() => {
                //   console.debug("Will send 0xF3 request to msdk");
                //向msdk发送0xF3请求联网命令
                var msdk17CmdArr = cloudComSerial.serialMsdkCmdArrayPack(0xF3, "01")
                cloudComSerial.sendCmd(msdk17CmdArr);
            }, 3000);
            //跳转成功页面
            connectingState = 1
            // gotoConnectSuccessPage()
        } else {
            console.log("Connect wifi failed");
            //跳转失败页面
            connectTimeout = 70
            // gotoConnectFailedPage()
        }
    });
    //跳转正在连接页面
    // gotoConnectingPage()
}
// proxy.on("onInstallationGeneralSettingConnectWifi", onInstallationGeneralSettingConnectWifi);


function ConnectWifi(value) {
    var ssid = connectWifiSSID;
    var pwd = value;
    var encrypte = _encryptedMode;
    // console.log("ConnectWifi: " + ssid + "pwd: " + pwd + "encrypte: " + encrypte);
    // var factory_wifi = require("factory_wifi.js");
    // factory_wifi.testWifiConnect(ssid, pwd);
    // connect_wifi(ssid,pwd);
    that.initWifissid = ssid;
    that.initWifipwd = pwd;
    that.initencryptedMode = encrypte;
    // console.log("that.initWifissid: " + that.initWifissid + "that.initWifipwd: " + that.initWifipwd + "that.initencryptedMode: " + that.initencryptedMode);
    that.InterValTime();
    // console.log("===================ConnectWifi: " + that.initWifissid + "--pwd: " + that.initWifipwd);
}

function enableWLANScanValue() {
    console.log("Is @@@@@@@@@@@@@@@@@@@@@@@@@@#3333333")
    // if (!userData.enableWLANSwitchFlag) {
    //     return;
    // }
    var process = require("@system.process")
    if (process.platform == "win32") {
        console.log("its win32.")
        return;
    }
    console.log("resultsWifiList:")
    if (resultsWifiList && oneFlag) {
        scanRefreshWifiList(resultsWifiList)
        oneFlag = 0;
    }

    systemCtrl.executeSystemCommand("rm -fr /tmp/scan_result.txt")
    systemCtrl.executeSystemCommand("wpa_cli -p /tmp/wpa_supplicant/sockets scan")
    setTimeout(function () {

        systemCtrl.executeSystemCommand("wpa_cli -p /tmp/wpa_supplicant/sockets scan_results > /tmp/scan_result.txt")
        var content = fs.read("/tmp/scan_result.txt", "r")
        if (content) {

            var listScanValue = parseWifiScanResults(content)
            if (listScanValue.length > 0) {
                resultsWifiList = listScanValue;
                console.log(JSON.stringify(resultsWifiList))
            }
            // resultsWifiList = parseWifiScanResults(content)
            // console.log(JSON.stringify(resultsWifiList))
            // refreshWifiList(resultsWifiList)
        }
    }, 5000)
}


//touchedStartScanWifiDetailsButton 点击开始扫描
//touchedscanWifiList 进入wifi列表页面
module.exports = {
    enableWLANSwitch: enableWLANSwitch,
    connect_wifi: connect_wifi,
    getWifiInfo: getWifiInfo,
    testWifiInitPage: testWifiInitPage,
    ConnectWifi: ConnectWifi,
    enableWLANScanValue: enableWLANScanValue,


}