
var systemCtrl = require("systemCtrl.js");
var egenmd5 = require("factory_egenmd5.js");
var process = require("@system.process");
/**
 * 提取文件路径中的名称（含扩展名）
 * @param {string} path 文件的相对路径（如 "src/file.txt" 或 "data.json"）
 * @returns {string} 文件名（如 "file.txt"）
 */
function getFileName(path) {
    // 处理路径末尾的冗余斜杠（如 "docs/" → "docs"）
    const trimmedPath = path.endsWith('/') ? path.slice(0, -1) : path;
    // 分割路径并取最后一段
    return trimmedPath.split('/').pop();
}
function create(name) {
    var fs = require("@system.fs")
    var ret = 0
    var obj = {
        "create": 0
    }
    //  获取文件名
    var filenm = getFileName(name)

    if (process.platform == "win32") {
        ret = fs.writeFile(filenm, JSON.stringify(obj));
    } else {
        //构造相对路径
        var partAFilePath = "../../../../../mnt/userdataA/files/" + filenm
        var partBFilePath = "../../../../../mnt/userdataB/files/" + filenm
        // 获取绝对路径
        var partAFilePath_abs = "/mnt/userdataA/files/" + filenm
        var partBFilePath_abs = "/mnt/userdataB/files/" + filenm
        //写A区文件
        ret = fs.writeFile(partAFilePath, JSON.stringify(obj));
        systemCtrl.executeSystemCommand("fsync " + partAFilePath_abs);
        egenmd5.update("/mnt/userdataA/files", "/mnt/userdataA/userdata.md5");
        //写B区文件
        ret = fs.writeFile(partBFilePath, JSON.stringify(obj));
        systemCtrl.executeSystemCommand("fsync " + partBFilePath_abs);
        egenmd5.update("/mnt/userdataB/files", "/mnt/userdataB/userdata.md5");
    }
    if (ret == 0) {
        //console.log(name + " Created Successfully.")
    } else {
        //console.log(name + " Created Failed")
        //console.log("create ErrorCode:" + ret)
    }
}
function write(name, obj) {
    var fs = require("@system.fs")
    // 新增参数校验逻辑
    if (typeof obj === 'undefined' || obj === null || obj === "") {
        //console.log("Error: Invalid input object");
        return;
    }
    let tempStr;
    if (typeof obj === 'string') {
        tempStr = obj;
    } else {
        try {
            tempStr = JSON.stringify(obj);
        } catch (e) {
            //console.log("Error: Object serialization failed");
            return;
        }
    }

    // //console.log(obj)
    //  获取文件名
    var filenm = getFileName(name)

    if (process.platform == "win32") {
        ret = fs.writeFile(filenm, JSON.stringify(obj));
    } else {
        //构造相对路径
        var partAFilePath = "../../../../../mnt/userdataA/files/" + filenm
        var partBFilePath = "../../../../../mnt/userdataB/files/" + filenm
        // 获取绝对路径
        var partAFilePath_abs = "/mnt/userdataA/files/" + filenm
        var partBFilePath_abs = "/mnt/userdataB/files/" + filenm

        //写A区文件
        var ret = fs.writeFile(partAFilePath, tempStr);
        systemCtrl.executeSystemCommand("fsync " + partAFilePath_abs);
        egenmd5.update("/mnt/userdataA/files", "/mnt/userdataA/userdata.md5");
        //写B区文件
        var ret = fs.writeFile(partBFilePath, tempStr);
        systemCtrl.executeSystemCommand("fsync " + partBFilePath_abs);
        egenmd5.update("/mnt/userdataB/files", "/mnt/userdataB/userdata.md5");
    }

    if (ret == 0) {
        //console.log(name + " write Successfully.")
    } else {
        //console.log(name + " write Failed")
        //console.log("write ErrorCode:" + ret)
    }
}

function check(name, obj) {
    var fs = require("@system.fs")
    var filenm = getFileName(name)
    //构造相对路径
    if (process.platform == "win32") {
        var partFilePath = "./" + filenm
    } else {
        var partFilePath = "../../../../../mnt/userdataA/files/" + filenm
    }
    if (fs.exists(partFilePath)) {
        //console.log("the " + name + " is exists.")
        return 0
    } else {
        return -1
    }
}
function read(name, mode) {
    var fs = require("@system.fs")
    //console.log("In Read function name is :" + name)
    var filenm = getFileName(name)
    //构造相对路径
    if (process.platform == "win32") {
        var partFilePath = "./" + filenm
    } else {
        var partFilePath = "../../../../../mnt/userdataA/files/" + filenm
    }

    if (check(partFilePath)) {
        return undefined
    }
    //console.log("In Read function path is :" + partFilePath);
    if (mode == "json") {
        var ret = fs.readFile(partFilePath, "r")
        var data = JSON.parse(ret)
    } else {
        var ret = fs.readFile(partFilePath, "rb")
        var data = ret
    }
    //console.log(data)
    return data
}

function checkBasicPath(name, obj) {
    var fs = require("@system.fs")
    if (fs.exists(name)) {
        //console.log("the " + name + " is exists.")
        return 0
    } else {
        return -1
    }
}

function readBasicPath(name, mode) {
    var fs = require("@system.fs")
    //console.log("In readBasicPath name = " + name)
    //console.log("In readBasicPath mode = " + mode)
    //console.log("In readBasicPath checkBasicPath(name) = " + checkBasicPath(name))
    if (checkBasicPath(name)) {
        return undefined
    }
    if (mode == "json") {
        var ret = fs.readFile(name, "r")
        var data = JSON.parse(ret)
    } else {
        var ret = fs.readFile(name, "rb")
        var data = ret
    }
    return data
}


module.exports = {
    check: check,
    create: create,
    read: read,
    write: write,
    readBasicPath: readBasicPath,
}

