
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_testRtcTimer = null;
var that;
var rtcCtl = require("factory_rtc.js");
var cntTime = 0;
var cntSuccess = 0;
var checkClockPath = '../../../../../mnt/UDISK/checkClock.txt';
var checktmpClockPath = '../../../../../tmp/checkClock.txt';
var Path = "/mnt/UDISK/checkClock.txt";
var tmpPath = "/tmp/checkClock.txt";
function system(str) {
    systemCtrl.executeSystemCommand(str);
}


function exitTestRTC() {
    if (id_testRtcTimer != null) {
        clearInterval(id_testRtcTimer);
        id_testRtcTimer == null;
    }
}

function factoryTestRTCInit(obj) {
    that = obj;
    if (id_testRtcTimer != null) {
        clearInterval(id_testRtcTimer);
        id_testRtcTimer == null;
        cntTime = 0;
        cntSuccess = 0;
    }
    that.crtfilesLocalTime = "NA";
    updateRtcInfo();
    id_testRtcTimer = setInterval(() => {
        cntTime += 1;
        updateRtcInfo();
    }, 1000);
}
function setTextColorById(that, id, value) {
    const color = (value === "NA") ? "#ff0000" : "#00ff00";
    that.$setTextColor(id, color);
}
function setTextColorByText(that, id, value) {
    var color;
    if (value === "测试失败") {
        color = "#ff0000";
    }
    else if (value === "ING") {
        color = "#ff8400";
    }
    else if (value === "RTCERROR") {
        color = "#ff0000";
    }
    else if (value === "RTCSUCCESS") {
        color = "#00ff00";
    }
    else {
        color = "#00ff00";
    }
    that.$setTextColor(id, color);
}




function updateRtcInfo() {

    const testCnt = 3  //测试3次

    var g = getRtcTime();
    var rtc = g.time
    that.crtLocalTime = rtc;
    //console.log("hwRtc:" + rtc);

    const allValuesValid = g.err === 0; //0为成功检测到时间
    console.log(`[RTC] 第 ${cntTime} 次检测，状态：${allValuesValid == true ? "有效" : "无效"}`);
    if (allValuesValid) {
        cntSuccess += 1;
    } else {
        cntSuccess = 0;
    }

    if (cntTime < testCnt) {
        if (g.err == 1) {
            setRtcTime();
            console.log("!!g.msg:" + g.msg);
            setTextColorByText(that, 'id_crtTextRtcText', "RTCERROR");
            that.crtTextRtcText = g.msg + ", 开始初始化RTC时间";

        } else {
            that.crtTextRtcText = "检测中...";
            setTextColorByText(that, 'id_crtTextRtcText', "ING");
        }
        that.$setY("id_yes", -480);
        return; // 不继续判断
    }

    // 第2次检测完成，设置最终结果
    if (cntSuccess > testCnt) {
        if (!fs.exists(checktmpClockPath)) {

            if (fs.exists(checkClockPath)) {

                var fileContent = fs.read(Path, "r")
                if (fileContent) {

                    that.crtfilesLocalTime = fileContent.trim();

                    var fileYMD = parseYMDHM(fileContent.trim());
                    var currYMD = parseYMDHM(that.crtLocalTime);
                    if (!timeGT(currYMD, fileYMD)) {
                        console.log("[RTC] 时钟未前进，测试失败");
                        cntSuccess = 0;
                        var state = 0;
                        var text = state ? "测试通过" : "测试失败";
                        that.crtTextRtcText = text + ",如需RTC时间流逝测试,请重进"
                        setTextColorByText(that, 'id_crtTextRtcText', that.crtTextRtcText);
                        //globalThis.factoryTest.rtc = state ? 1 : 2;
                        var testVal = state ? 1 : 2;
                        that.$setY("id_yes", state ? 0 : -480);
                        console.log("[RTC] 测试完成，最终状态：" + (state ? "通过" : "失败"));
                    } else {
                        console.log("fileYMD" + fileContent.trim());
                        console.log("currYMD:" + that.crtLocalTime);
                        console.log("[RTC] 时钟已前进，继续通过流程");
                        system("rm -fr " + Path);
                        var state = 1;
                        var text = state ? "测试通过" : "测试失败";
                        that.crtTextRtcText = text + ",如需RTC时间流逝测试,请重进"
                        setTextColorByText(that, 'id_crtTextRtcText', that.crtTextRtcText);


                        //globalThis.factoryTest.rtc = state ? 1 : 2;
                        var testVal = state ? 1 : 2;
                        that.$setY("id_yes", state ? 0 : -480);
                        console.log("[RTC] 测试完成，最终状态：" + (state ? "通过" : "失败"));
                        var global = require("factory_dataStorage.js");

                    }
                    var global = require("factory_dataStorage.js");
                    global.setFactoryData("rtc", testVal);
                    //  if (testVal == 2) {
                    exitTestRTC();
                    //}
                } else {
                    oneTest();
                }

            } else {
                oneTest();
            }
        } else {
            oneTest();
        }
    } else {

        if (cntSuccess <= 0) {
            setRtcTime();
            that.crtTextRtcText = g.msg + ",RTC无效效时间!";
            setTextColorByText(that, 'id_crtTextRtcText', "RTCERROR");
        }
        else {

        }
    }


    checkAutoFactory();

}

function oneTest() {
    var iso = that.crtLocalTime;
    system("echo '" + iso + "' > " + Path);
    that.crtfilesLocalTime = iso;
    system("echo '" + iso + "' > " + tmpPath);
    system("sync");
    console.log("[RTC] one tets ok");
    setTextColorByText(that, 'id_crtTextRtcText', "ING");
    that.crtTextRtcText = "请断电重启 测试第二阶段掉电保存"

}

function checkAutoFactory() {
    require("factory_testAuto.js").autoFactoryNextPage("factoryTestRtc");
}
function parseYMDHM(str) {
    // str = "2025-10-03T19:41:38"
    var p = str.split('T');
    var d = p[0].split('-').map(Number);   // [y, m, d]
    var t = p[1].split(':').map(Number);   // [h, m, s]
    return { y: d[0], m: d[1], d: d[2], h: t[0], min: t[1], s: t[2] };
}

function timeGT(a, b) {
    // a > b 返回 true
    if (a.y !== b.y) return a.y > b.y;
    if (a.m !== b.m) return a.m > b.m;
    if (a.d !== b.d) return a.d > b.d;
    if (a.h !== b.h) return a.h > b.h;
    if (a.min !== b.min) return a.min > b.min;
    return a.s > b.s;
}

/**
 * 读取 RTC 并检测异常
 * @returns {obj}  {err: 0|1,  msg: '',  time: ''}
 *   err=0 正常；err=1 异常
 */
function getRtcTime() {

    const partFilePath = "../../../../../dev/rtc1";
    if (!fs.exists(partFilePath)) {
        return { err: 1, msg: 'RTC device not found', time: 'NA' };
    }

    // 1. 执行 hwclock
    system('hwclock -f /dev/rtc1 > /tmp/hwRtc.txt 2>&1'); // 把 stderr 也重定向
    const raw = fs.read('/tmp/hwRtc.txt');
    if (!raw) return { err: 1, msg: 'Read empty', time: 'NA' };

    // 2. 检测 Invalid argument
    if (raw.includes('Invalid argument')) {
        return { err: 1, msg: 'Invalid argument', time: 'NA' };
    }

    /* 3. 正常解析年月日时分秒（沿用你原逻辑） */
    const monTbl = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
        'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    let p = 0;
    // 星期
    while (p < raw.length && raw[p] !== ' ') p++;
    while (p < raw.length && raw[p] === ' ') p++;
    // 月
    let monSt = p;
    while (p < raw.length && raw[p] !== ' ') p++;
    const mon = raw.slice(monSt, p);
    while (p < raw.length && raw[p] === ' ') p++;
    // 日
    let daySt = p;
    while (p < raw.length && raw[p] !== ' ') p++;
    const day = raw.slice(daySt, p).trim();
    while (p < raw.length && raw[p] === ' ') p++;
    // 时间
    let timeSt = p;
    while (p < raw.length && raw[p] !== ' ') p++;
    const timeFull = raw.slice(timeSt, p);      // HH:MM:SS[.xxx]
    const time = timeFull.split('.')[0];
    while (p < raw.length && raw[p] === ' ') p++;
    // 年
    let yearSt = p;
    while (p < raw.length && raw[p] !== ' ') p++;
    const year = raw.slice(yearSt, p);

    const mo = monTbl.indexOf(mon) + 1;
    if (mo === 0) return { err: 1, msg: 'Month parse fail', time: '1970-01-01T00:00:00' };

    const iso = `${year}-${String(mo).padStart(2, '0')}-${String(day).padStart(2, '0')}T${time}:00`;

    // 4. 1970 年判定
    if (year.startsWith('1970')) {
        return { err: 1, msg: 'RTC time is 1970', time: iso };
    }

    // 5. 正常
    return { err: 0, msg: '', time: iso };
}


function setRtcTime() {
    //date -s "1970-10-03 19:50:00"
    //hwclock -w -f /dev/rtc1
    var librtc = require("rtc.js");
    librtc.ctrl("set", {
        year: userData.time.year,
        month: userData.time.month,
        day: userData.time.day,
        hour: userData.time.hour,
        minute: userData.time.minute,
        second: 0,
    });
}

module.exports = {
    factoryTestRTCInit: factoryTestRTCInit,
    exitTestRTC: exitTestRTC,
}