const koffi = require('koffi');
let Codeobj = [];
let CodeNameObj = {};
let CallbackObj = {};
exports.insertCode = function (file, code) {
    let RetInt = Codeobj.length;
    Codeobj[RetInt] = koffi.load(file);
    for (let key in code) {
        if (typeof (code[key]) == 'string') {
            CodeNameObj[key + RetInt] = Codeobj[RetInt].func(code[key]);
        } else {
            if (code[key][0] == "注册函数") {
                if (code[key][1]["返回类型"] == undefined || code[key][1]["返回类型"]=="") {
                    code[key][1]["返回类型"] = "void"
                }
                let CallbackCs = ""
                for (let index = 0; index < code[key][1]["函数参数"].length; index++) {
                    if (index == code[key][1]["函数参数"].length - 1) {
                        CallbackCs = CallbackCs + code[key][1]["函数参数"][index] + " c" + index
                    } else {
                        CallbackCs = CallbackCs + code[key][1]["函数参数"][index] + " c" + index + ","
                    }
                }
                const GetCallback = koffi.proto(code[key][1]["返回类型"] + " " + code[key][1]["回调函数名称"] + "(" + CallbackCs + ")");
                CodeNameObj[key + RetInt] = Codeobj[RetInt].func(code[key][1]["函数整体"]);
                let cb1 = koffi.register((...args) => {
                    return code[key][1]["回调函数"](...args)
                }, koffi.pointer(GetCallback));
                CallbackObj[key + RetInt] = cb1;
            } else {
                if (code[key].length >= 2) {
                    CodeNameObj[key + RetInt] = Codeobj[RetInt].func(key, code[key][0], code[key][1]);
                }
            }
        }
    }
    return RetInt;
}
exports.struct = function (name, struct_) {
    return koffi.struct(name,struct_)
}
exports.GetCallback = function (name, int_ = 0) {
    return CallbackObj[name + int_];
}
exports.RetCodeList = function (name, int_ = 0) {
    return CodeNameObj[name + int_];
}