var dlfcn = require("dlfcna.js");

//console.log(dlfcn)

var funcs = [
    ["executeSync", "vi"],
    ["testPrint", "ii"],
    ["executeUpdate", "ii"],
    ["systemMain", "vi"],
    ["systemReboot", "vi"],
    ["findSwuFile", "ii"],
    ["checkPartition", "ii"],
    ["executeSystemCommand", "is"],
    ["executePrint", "is"],
];

//console.log("in systemCtrl.js")
function register() {
    if (globalThis.$simulatorFlag == true) {
        return undefined
    }
    var process = require("@system.process")
    if (process.platform == "win32") {
        //console.log("***will register win32_register_func*****")
        const Win32RegFunc = require("win32_register_func.js").Win32RegFunc;
        var win32Reg = new Win32RegFunc(funcs);
        return win32Reg;
    }
    //console.log("will register systemCtrl.so")
    var isSuccess = dlfcn.register("@native.systemCtrl", "./lib/factory/systemCtrl.so", funcs);
    if (isSuccess) {
        //console.log("load so successfully")
        var systemCtrl = require("@native.systemCtrl");
        return systemCtrl
    } else {
        //console.log("load so failed")
    }
    return undefined;
}
var systemCtrl = register();

function sync(value) {
    systemCtrl.executeSync(value);
}

function findSwuFile(value) {
    //console.log("There are in findSwuFile function! ");
    var findSwuFlag = 0;
    findSwuFlag = systemCtrl.findSwuFile(value);
    //console.log("findSwuFlag=" + findSwuFlag);
    return findSwuFlag;

}

function executeSwuUpdate(value1, value2) {
    var updateFlag = 0;//升级成功置为1，失败置为0
    if ((value1 == 1 || value1 == 0) && (value2 == 1)) {
        updateFlag = systemCtrl.executeUpdate(value1);
    }
    //console.log("updateFlag=" + updateFlag);
}

function executeSystemCommand(cmd) {
    var executeFlag = systemCtrl.executeSystemCommand(cmd);
    // //console.log("executeFlag=" + executeFlag);
    // if (executeFlag == -1) {
    //     //console.log("executeSystemCommand failed!");
    // }
    // else {
    //     //console.log("executeSystemCommand success!");
    // }
}

function executePrint(str) {
    //console.log("There are in executePrint function! ");
    var executeFlag = systemCtrl.executePrint(str);
}


function systemReboot(value) {
    systemCtrl.systemReboot(value);
    //console.log("There are in systemReboot function! ");
}

function checkPartition(value) {
    //console.log("There are in checkPartition function! ");
    var checkValue = systemCtrl.checkPartition(value);
    //console.log("checkValue=" + checkValue);
    return checkValue;
}

function systemMain(value) {
    systemCtrl.systemMain(value);
    //console.log("There are in systemMain function! ");
}

module.exports = {
    sync: sync,
    findSwuFile: findSwuFile,
    systemMain: systemMain,
    systemReboot: systemReboot,
    checkPartition: checkPartition,
    executeSwuUpdate: executeSwuUpdate,
    executeSystemCommand: executeSystemCommand,
    executePrint: executePrint,
}