
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 writeWpaConf = require("factory_writeWpaConf.js")


var resultsWifiList = undefined;
var that;
var wifi_div = undefined;
var wifi_list_div = undefined;
var cnt = 0;
var connectWifiSSID = null;
var signalLevel = 0;
var _encryptedMode = "";

var oneFlag = 1;

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+/);
        if (parts.length < 4) continue;

        const bssid = parts[0];
        const frequency = parseInt(parts[1], 10); // MHz
        const signalLevel = parseInt(parts[2], 10); // dBm
        const flags = parts[3];
        const ssid = parts.slice(4).join(' ') || ''; // 可能含空格

        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';

        results.push({
            ssid: ssid,
            bssid: bssid,
            frequency: frequency, // ← 新增
            signalLevel: signalLevel,
            isEncrypted: encryptedMode !== 'Open',
            encryptedMode: encryptedMode
        });
    }
    return results;
}
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, mode) {
//     console.log("===============connect_wifi: " + ssid + "===psk: " + psk + "===mode: " + mode);
//     writeWpaConf.set(ssid, psk, mode)
//     systemCtrl.executeSystemCommand("/tmp/wlanInit.sh &") //重启wifi连接
//     return

// }
function connect_wifi(wifi) {
    // 写配置时增加 bssid 字段
    if (wifi.bssid == undefined) {
        var bssid = '';
    } else {
        var bssid = wifi.bssid;

    }
    console.log("connectBestWifi: " + JSON.stringify(wifi));
    writeWpaConf.set(wifi.ssid, wifi.pwd, wifi.mode, bssid);   // 内部生成 network={ssid="xxx" psk="xxx" bssid=XX:XX:XX:XX:XX:XX}
    systemCtrl.executeSystemCommand("/tmp/wlanInit.sh &");
}

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++) {

        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)

        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")

    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, bssid) {
    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;
    var bssidFlag = false;
    if (bssid != undefined) {
        bssidFlag = true;
    }
    for (let i = 0; i < resultsWifiList.length; i++) {
        if (resultsWifiList[i].ssid === ssid && (bssidFlag && bssid === resultsWifiList[i].bssid)) {
            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 ConnectWifi(value) {
    var ssid = connectWifiSSID;
    var pwd = value;
    var encrypte = _encryptedMode;

    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")

    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))
            }
        }
    }, 5000)
}
function pickStrongestBySsid(list, targetSsid) {
    console.log("pickStrongestBySsid");
    let best = null;

    list.forEach(item => {
        if (item.ssid === targetSsid) {
            console.log("candidate item:" + JSON.stringify(item));
            if (!best || item.signalLevel > best.signalLevel) {
                best = item;
            }
        }
    });

    console.log("best:" + JSON.stringify(best));
    return best;
}
function getScanAllWifi() {
    console.log("getScanAllWifi");
    if (!resultsWifiList || resultsWifiList.length === 0) {
        // enableWLANScanValue();
        return [];
    }
    return resultsWifiList || [];
}

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

}