
var _userdata = require("userdata.js");
var userData = _userdata.userData;
const fs = require("@system.fs");
var systemCtrl = require("systemCtrl.js");
var lvgl = require("@native.lvgl7");
var id_testBurnInTimer = null;
var that;
var strMemtesterCnt = 0; // 初始化测试掩码计数器
var exStopagainMp4Flag = false;
var testVal;
// 测试掩码映射表
const testMaskMap = {
    "0x1": "Compare XOR",
    "0x2": "Compare SUB",
    "0x4": "Compare MUL",
    "0x8": "Compare DIV",
    "0x10": "Compare OR",
    "0x20": "Compare AND",
    "0x40": "Sequential Increment",
    "0x80": "Solid Bits",
    "0x100": "Block Sequential",
    "0x200": "Checkerboard",
    "0x400": "Bit Spread",
    "0x800": "Bit Flip",
    "0x1000": "Walking Ones",
    "0x2000": "Walking Zeroes",
    "0x4000": "8-bit Writes",
    "0x8000": "16-bit Writes"
};
function system(str) {
    system(str);
}
function initFactoryTestBurnIn(obj) {
    that = obj;
    startMp4();
    if (id_testBurnInTimer != null) {
        clearInterval(id_testBurnInTimer);
        id_testBurnInTimer == null;
    }
    updateBurnInInfo();
    id_testBurnInTimer = setInterval(() => {
        updateBurnInInfo();
    }, 5000);

    // var result = getMemtesterData2("32M");
    // //console.log('Memtester Result:'+ result);
    // setInterval(() => {
    //     // 调用 getMemtesterData 函数，指定测试内存大小为 32M，并处理结果
    //     var result = getMemtesterData2("32M");
    //     //console.log('Memtester Result:'+ result);
    // }, 20000);

}

function quitFactoryTestBurnIn() {

    var global = require("factory_dataStorage.js");
    global.setFactoryData("burnIn", testVal);


    system("killall -9 memtester 2>/dev/null")
    //console.log("quitFactoryTestBurnIn");
    if (id_testBurnInTimer != null) {
        clearInterval(id_testBurnInTimer);
        id_testBurnInTimer == null;
    }

    exitMp4();
}


function system(com) {
    systemCtrl.executeSystemCommand(com)
}
var id_mp4Timer = null;
var id_mp4exitTimer = null;
function startMp4() {
    if (id_mp4Timer != null) {
        clearInterval(id_mp4Timer);
        id_mp4Timer == null;
    }

    id_mp4Timer = setTimeout(() => {
        // lvgl.lv_set_screen_transparent(true);
        system("tplayerdemo /mnt/app/quicknode/tests/re860_factory/images/factory/testVideo240p.mp4 > /dev/null 2>&1 &");
    }, 200);
}

function exitMp4() {
    // if (id_mp4exitTimer != null) {
    //     clearInterval(id_mp4exitTimer);
    //     id_mp4exitTimer == null;
    // }
    // id_mp4exitTimer = setTimeout(() => {
    // lvgl.lv_set_screen_transparent(false);


    // 1. 温和退出
    system("killall -2 tplayerdemo 2>/dev/null");

    setTimeout(() => {
        // 2. 空跑一次 tplayerdemo（静默后台）
        system("tplayerdemo > /dev/null 2>&1 &");

        // 3. 马上再杀掉
        setTimeout(() => {
            system("killall -9 tplayerdemo 2>/dev/null");
        }, 100);   // 100 ms 足够让进程起来
    }, 200);       // 200 ms 给第一次退出留时间
    // }, 500);

    exStopagainMp4Start();
}

function exStopagainMp4Start() {
    exStopagainMp4Flag = true;
}
function exStopagainMp4Stop() {
    exStopagainMp4Flag = false;
}

function exStopagainMp4() {
    if (exStopagainMp4Flag == true) {
        system("killall -2 tplayerdemo 2>/dev/null");

        setTimeout(() => {
            // 2. 空跑一次 tplayerdemo（静默后台）
            system("tplayerdemo > /dev/null 2>&1 &");

            // 3. 马上再杀掉
            setTimeout(() => {
                system("killall -9 tplayerdemo 2>/dev/null");
            }, 100);   // 100 ms 足够让进程起来
        }, 200);       // 200 ms 给第一次退出留时间
        exStopagainMp4Stop();
    }
}

function setTextColorById(that, id, value) {
    const color = (value === "NA") ? "#ff0000" : "#00ff00";
    that.$setTextColor(id, color);
}
var cntMemtester = 2;
var testMask = 0x1;
var commFlag = 1;


function setTextColorByMemtester() {
    // 0 = 绿色，1 = 红色
    const memColor = that.crtMemorycrtMemtester.includes(': OK') ? '#00ff00' : '#ff0000';
    that.$setTextColor('id_crtMemorycrtMemtester', memColor);
}
function updateBurnInInfo() {
    that.crtCPUModel = getCPUModel();
    that.crtCPUCores = getCPUCores();
    that.crtCurrentFrequency = getCPUFrequency();
    that.crtCpuLoad = getCPULoad();
    var logInfo = getMemoryInfo();
    that.crtMemoryTotal = logInfo.total;
    that.crtMemoryUsed = logInfo.used;
    that.crtMemoryAvailable = logInfo.available;



    cntMemtester++;
    if (cntMemtester >= 2) {
        if (commFlag == 1) {
            var testSize = getTestMemorySize(); // 获取测试内存大小
            //console.log("!!testSize:" + testSize);
            testMask = getTestMask();
            //console.log("!!testMask:" + testMask);
            startCommMemtester(testSize);
            commFlag = 0;
        } else {
            if (cntMemtester > 3) {
                var memtester = getMemtester() //只能返回testMaskMap映射表的值，比如testMask为0x1，则memtester只能为值为OK 或者no
                //console.log("memtester:" + memtester);
                cntMemtester = 0;
                commFlag = 1;
                that.crtMemorycrtMemtester = memtester;
                setTextColorByMemtester();
            }
        }
    }


    setTextColorById(that, 'id_crtCPUModel', that.crtCPUModel);
    setTextColorById(that, 'id_crtCPUCores', that.crtCPUCores);
    setTextColorById(that, 'id_crtCurrentFrequency', that.crtCurrentFrequency);
    setTextColorById(that, 'id_crtCpuLoad', that.crtCpuLoad);
    setTextColorById(that, 'id_crtMemoryTotal', that.crtMemoryTotal);
    setTextColorById(that, 'id_crtMemoryUsed', that.crtMemoryUsed);
    setTextColorById(that, 'id_crtMemoryAvailable', that.crtMemoryAvailable);


    var values = [that.crtCPUModel, that.crtCPUCores, that.crtCurrentFrequency, that.crtCpuLoad, that.crtMemoryTotal, that.crtMemoryUsed, that.crtMemoryAvailable];
    var allValuesValid = values.every(value => value !== "NA");
    // 根据检查结果设置烧录测试状态
    //globalThis.factoryTest.burnIn = allValuesValid ? 1 : 2;
    testVal = allValuesValid ? 1 : 2;

}


// 获取 CPU 型号
function getCPUModel() {
    system("cat /proc/cpuinfo > /tmp/cpuinfo.txt");
    const modelStr = fs.read("/tmp/cpuinfo.txt", "r");
    if (modelStr) {
        const modelMatch = modelStr.match(/model name\s*: (.+)/i);
        if (modelMatch) {
            const fullModel = modelMatch[1].trim();
            //console.log("CPU Model: " + fullModel);

            // 检查是否包含 "v7-M"，以决定输出哪个型号
            if (fullModel.includes("v7-M")) {
                return fullModel; // 输出更具体的型号，如 ARMv7-M rev 5 (v7l)
            } else {
                return fullModel.split(' ')[0]; // 只输出架构版本，如 ARMv7
            }
        } else {
            return "NA";
        }
    } else {
        return "NA";
    }
}
// 获取 CPU 核数
function getCPUCores() {
    system("grep -c ^processor /proc/cpuinfo > /tmp/cores.txt");
    const coresStr = fs.read("/tmp/cores.txt", "r");
    if (coresStr) {
        return coresStr.trim();
    } else {
        return "NA";
    }
}

// 获取当前 CPU 频率
function getCPUFrequency() {
    system("cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq > /tmp/cpu_freq.txt");
    const freqStr = fs.read("/tmp/cpu_freq.txt", "r");
    if (freqStr) {
        const freqMHz = parseInt(freqStr.trim()) / 1000;
        return freqMHz.toFixed(0) + " MHz";
    } else {
        return "NA";
    }
}

// 获取 CPU 负载
function getCPULoad() {
    system("uptime > /tmp/load.txt");
    const loadStr = fs.read("/tmp/load.txt", "r");
    if (loadStr) {
        const loadMatch = loadStr.match(/load average: (\d+\.\d+), (\d+\.\d+), (\d+\.\d+)/i);
        if (loadMatch) {
            return loadMatch[1];
        } else {
            return "NA";
        }
    } else {
        return "NA";
    }
}

// 获取内存信息
function getMemoryInfo() {
    system("free -h > /tmp/meminfo.txt");
    const memStr = fs.read("/tmp/meminfo.txt", "r");
    if (memStr) {
        const lines = memStr.split('\n');
        if (!lines) {
            return "NG";
        }
        // 跳过表头
        for (let i = 1; i < lines.length; i++) {
            const line = lines[i].trim();
            if (line.startsWith("Mem")) {
                const parts = line.split(/\s+/);
                if (!parts) {
                    return "NG";
                }
                if (parts.length > 1) {
                    const memTotal = parts[1]; // 总量
                    const memUsed = parts[2]; // 使用量
                    const memAvailable = parts[parts.length - 2]; // 可用内存通常在倒数第二个位置
                    //内存总量、空闲总量、使用总量
                    //console.log('Memory Info:memTotal:' + memTotal + ' memUsed:' + memUsed + ' memAvailable:' + memAvailable);
                    return {
                        total: memTotal,
                        used: memUsed,
                        available: memAvailable
                    };
                }
                break;
            }
        }
        return "NG";
    } else {
        return "NG";
    }
}
function delayExecute(func, delay) {
    setTimeout(func, delay);
}

var id_testBurnInTimer2 = null;

// 延迟执行函数
function delayExecute(func, delay) {
    // 如果已经存在定时器，先清除
    if (id_testBurnInTimer2 != null) {
        clearTimeout(id_testBurnInTimer2);
        id_testBurnInTimer2 = null;
    }
    // 设置新的定时器
    id_testBurnInTimer2 = setTimeout(func, delay);
}
// function getTestMask() {
//     // 生成测试掩码值
//     const testMasks = [
//         "0x1",  // Compare XOR
//         "0x2",  // Compare SUB
//         "0x4",  // Compare MUL
//         "0x8",  // Compare DIV
//         "0x10", // Compare OR
//         "0x20", // Compare AND
//         "0x40", // Sequential Increment
//         "0x80", // Solid Bits
//         "0x100", // Block Sequential
//         "0x200", // Checkerboard
//         "0x400", // Bit Spread
//         "0x800", // Bit Flip
//         "0x1000", // Walking Ones
//         "0x2000", // Walking Zeroes
//         "0x4000", // 8-bit Writes
//         "0x8000"  // 16-bit Writes
//     ];

//     // 更新计数器
//     strMemtesterCnt = (strMemtesterCnt + 1) % testMasks.length;
//     return testMasks[strMemtesterCnt];
// }



function getTestMask() {
    const testMasks = Object.keys(testMaskMap); 4
    strMemtesterCnt = (strMemtesterCnt + 1) % testMasks.length;
    return testMasks[strMemtesterCnt];
}
function startCommMemtester(testSize) {
    var testCount = 1;
    var str = `memtester -m ${testMask} ${testSize} ${testCount} > /tmp/memtester.txt`;
    //console.log(str);
    system(str);
}


function getMemtester() {
    // 读取测试结果
    const memtesterStr = fs.read("/tmp/memtester.txt", "r");
    if (memtesterStr) {
        // 解析测试结果
        const lines = memtesterStr.split('\n');
        const testResult = lines.find(line => line.includes(testMaskMap[testMask]));
        if (testResult) {
            if (testResult.includes(": ok")) {
                return `${testMaskMap[testMask]}: OK`;
            } else {
                return `${testMaskMap[testMask]}: error`;
            }
        } else {
            return "NA";
        }
    } else {
        return "NA";
    }
}


// 获取系统可用内存
function getAvailableMemory() {
    system("free -h > /tmp/meminfo.txt");
    const memStr = fs.read("/tmp/meminfo.txt", "r");
    if (memStr) {
        const lines = memStr.split('\n');
        if (!lines) {
            return "NG";
        }
        for (let i = 1; i < lines.length; i++) {
            const line = lines[i].trim();
            if (line.startsWith("Mem")) {
                const parts = line.split(/\s+/);
                if (parts.length > 1) {
                    const memAvailable = parts[6]; // 可用内存通常在第7个位置
                    return memAvailable;
                }
            }
        }
    }
    return "NA";
}

// 根据系统可用内存设置测试内存大小
function getTestMemorySize() {
    const availableMemory = getAvailableMemory();
    if (availableMemory === "NA") {
        //console.log("Failed to get available memory");
        return "64M"; // 默认值
    }

    const memValue = parseFloat(availableMemory);
    if (isNaN(memValue)) {
        //console.log("Invalid memory value:", availableMemory);
        return "64M"; // 默认值
    }

    // 将 KB 转换为 MB（1MB = 1024 KB）
    const memValueInM = (memValue / 1024).toFixed(0);
    //console.log(`Available Memory: ${memValueInM}M`);

    // 计算测试内存大小（空闲内存的 80%）
    const testSizeInM = (memValueInM * 0.5).toFixed(0);
    //console.log(`Test Memory Size: ${testSizeInM}M`);
    return testSizeInM + 'M'; // 返回 MB 单位的测试内存大小
}


function getLogInfo() {
    system("dmesg | grep -i memory > /tmp/loginfo.txt");
    delayExecute(() => {
        const logInfoStr = fs.read("/tmp/loginfo.txt", "r");
        if (logInfoStr) {
            //console.log('Log Info:' + logInfoStr);
            return logInfoStr;
        } else {
            console.error('Failed to read log info');
            return "NA";
        }
    }, 100); // 延迟100毫秒以确保文件写入完成
}
// 获取磁盘信息
function getDiskInfo() {
    system("df -h > /tmp/diskinfo.txt");
    delayExecute(() => {
        const diskInfoStr = fs.read("/tmp/diskinfo.txt", "r");
        if (diskInfoStr) {
            //console.log('Disk Info:' + diskInfoStr);
            return diskInfoStr;
        } else {
            console.error('Failed to read disk info');
            return "NA";
        }
    }, 100); // 延迟100毫秒以确保文件写入完成
}


module.exports = {
    initFactoryTestBurnIn: initFactoryTestBurnIn,
    quitFactoryTestBurnIn: quitFactoryTestBurnIn,
    exStopagainMp4: exStopagainMp4,

}