/*
文件名:LogClass.nut
路径:Dps_A/BaseClass/LogClass/LogClass.nut
创建日期:2024-10-10	11:35
文件用途:日志类
*/
class Log {

    //linux创建文件夹
    // function api_mkdir(path) {
    // 	var path_ptr = Memory.allocUtf8String(path);
    // 	if (opendir(path_ptr))
    // 		return true;
    // 	return mkdir(path_ptr, 0x1FF);
    // }
    _opendir_Address = Module.getExportByName(null, "opendir");
    _mkdir_Address = Module.getExportByName(null, "mkdir");


    Logger = null;
    LoggerBuffer = null;

    Coro = null;

    constructor(Info) {
        Logger = {};
        LoggerBuffer = {};

        local DirPath = Str_Ptr("/dp_s/log");
        if (!(Sq_CallFunc(_opendir_Address, "int", ["pointer"], DirPath))) {
            Sq_CallFunc(_mkdir_Address, "int", ["pointer", "int"], DirPath, 0x1FF);
        }

        //打开文件输出句柄
        foreach(Level, Path in Info) {

            try {
                local Io = IO(Path, "a");
                Logger[Level] <- Io;
                LoggerBuffer[Level] <- [];
            } catch (exception) {
                error("日志器初始化失败");
            }
        }

        getroottable()._Logger_Object_ <- this;
        Cb_timer_dispatch_Func.rawset("__System__Logger__Event", Update.bindenv(this));

        Coro = newthread(__Write__.bindenv(this));
    }


    function Put(Type, Message) {
        if (getroottable().rawin("_Logger_Object_")) {
            if (getroottable()._Logger_Object_.Logger.rawin(Type)) {
                getroottable()._Logger_Object_.LoggerBuffer[Type].push(Message);
                // getroottable()._Logger_Object_.Logger[Type].Write(Message);
                // getroottable()._Logger_Object_.Logger[Type].Flush();
            } else {
                error("未知的日志类型");
            }
        } else {
            error("未初始化日志器");
        }
    }

    function __Write__() {
        local ret = suspend("no");
        foreach(Type, MessageArr in LoggerBuffer) {
            for (local i = 0; i< MessageArr.len(); i++) {
                Logger[Type].Write(MessageArr[i]);
                Logger[Type].Flush();
                MessageArr.remove(i);
                i--;
                suspend("no");
            }
        }
        return "yes";
    }

    function Update() {
        local susparam = "noq";
        if (Coro.getstatus() == "idle") susparam = Coro.call();
        else if (Coro.getstatus() == "suspended") susparam = Coro.wakeup();

        if (susparam == "yes") {
            Coro = newthread(__Write__.bindenv(this));
        }
    }
}
