import fs from '@ohos.file.fs';
import taskpool from '@ohos.taskpool';
import hilog from '@ohos.hilog';
function f8(debug, path, u8) {
    "use concurrent";
    let v8 = fs.listFileSync(path);
    try {
        for (let w8 = 0; w8 < v8.length; w8++) {
            if (debug) {
            }
            fs.stat(`${path}/${v8[w8]}`).then((stat) => {
                if (new Date().getTime() - stat.mtime * 1000 > u8) {
                    fs.unlinkSync(`${path}/${v8[w8]}`);
                }
            });
        }
    }
    catch (err) {
    }
}
function g8(fd, message) {
    "use concurrent";
    if (fd === null) {
        return;
    }
    fs.writeSync(fd, `${message}\n`);
}
function h8(str) {
    return str !== null && str !== undefined && str !== '';
}
export class WLogger {
    setEnable(enable, t8) {
        this.isEnableLog = enable;
        this.prefix = t8;
    }
    setPrettyJson(enable) {
        this.prettyJson = enable;
    }
    registerCallback(s8) {
        this._loggerCb = s8;
    }
    localLogFileName(ctx, r8) {
        this.localLogName = r8;
        this.initLogFile(ctx);
    }
    format(date, format = 'yyyy-MM-dd HH:mm:ss.SSS') {
        let p8 = 2;
        let year = date.getFullYear().toString();
        let month = (date.getMonth() + 1).toString().padStart(p8, '0');
        let day = date.getDate().toString().padStart(p8, '0');
        let hour = date.getHours().toString().padStart(p8, '0');
        let minute = date.getMinutes().toString().padStart(p8, '0');
        let second = date.getSeconds().toString().padStart(p8, '0');
        let q8 = date.getMilliseconds().toString().padStart(p8 + 1, '0');
        let result = format.replace('yyyy', year);
        result = result.replace('MM', month);
        result = result.replace('dd', day);
        result = result.replace('HH', hour);
        result = result.replace('mm', minute);
        result = result.replace('ss', second);
        result = result.replace('SSS', q8);
        return result;
    }
    initLogFile(ctx) {
        let path = ctx.filesDir;
        let date = this.format(new Date(), 'yyyy-MM-dd');
        let result = `${path}/${this.logDirName}/${this.localLogName}-${date}.log`;
        if (this.debug) {
        }
        try {
            if (!fs.accessSync(`${path}/${this.logDirName}`)) {
                fs.mkdirSync(`${path}/${this.logDirName}`);
            }
            this.fileStream = fs.openSync(result, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE | fs.OpenMode.APPEND);
        }
        catch (err) {
            return;
        }
        taskpool.execute(f8, this.debug, `${path}/${this.logDirName}/`, this.expiredTime);
    }
    release() {
        this.localLogName = '';
        if (this.fileStream !== null) {
            fs.closeSync(this.fileStream);
            this.fileStream = undefined;
        }
    }
    constructor() {
        this.logDirName = "WALog";
        this.debug = false;
        this.isEnableLog = false;
        this.prefix = 'WA';
        this.expiredTime = 259200000;
        this.domain = 0x2600;
        this.prettyJson = false;
    }
    writeLog(o8) {
        if (this.isEnableLog && h8(this.localLogName)) {
            if (this.fileStream) {
                taskpool.execute(g8, this.fileStream?.fd, o8);
            }
        }
        return o8;
    }
    d(...args) {
        this.log(hilog.LogLevel.DEBUG, args);
    }
    i(...args) {
        this.log(hilog.LogLevel.INFO, args);
    }
    w(...args) {
        this.log(hilog.LogLevel.WARN, args);
    }
    e(...args) {
        this.log(hilog.LogLevel.ERROR, args);
    }
    log(level, args) {
        if (args.length == 0) {
            return;
        }
        let l8 = this.getLevelStr(level);
        let m8 = this.formatLog(args);
        let n8 = `${this.format(new Date())} | ${this.prefix} | [${l8}]-` + m8;
        if (this._loggerCb) {
            this._loggerCb(level, this.prefix, m8);
        }
        else {
            if (this.isEnableLog) {
                this.hiLog(level, args);
            }
            this.writeLog(n8);
        }
    }
    hiLog(level, args) {
        let k8 = [];
        let format = this.formatHiLog(k8, args);
        switch (level) {
            case hilog.LogLevel.INFO:
                hilog.info(this.domain, this.prefix, format, k8);
                break;
            case hilog.LogLevel.WARN:
                hilog.warn(this.domain, this.prefix, format, k8);
                break;
            case hilog.LogLevel.ERROR:
                hilog.error(this.domain, this.prefix, format, k8);
                break;
            case hilog.LogLevel.FATAL:
                hilog.fatal(this.domain, this.prefix, format, k8);
                break;
            default: hilog.debug(this.domain, this.prefix, format, k8);
        }
    }
    getLevelStr(level) {
        switch (level) {
            case hilog.LogLevel.DEBUG: return "DEBUG";
            case hilog.LogLevel.INFO: return "INFO";
            case hilog.LogLevel.WARN: return "WARN";
            case hilog.LogLevel.ERROR: return "ERROR";
            default: return "INFO";
        }
    }
    formatLog(args) {
        return args.map((v, index) => {
            if (v instanceof Object) {
                let prefix = this.prettyJson ? "\n" : "";
                let suffix = this.prettyJson ? "\n" : ",";
                return prefix + JSON.stringify(v, null, this.prettyJson ? "\t" : undefined) + suffix;
            }
            else {
                return v?.toString() + (index === 0 ? ":" : ",");
            }
        }).join("").slice(0, -1);
    }
    formatHiLog(arr, args) {
        let length = args.length;
        if (length === 0) {
            return "";
        }
        let format = "%{public}s";
        if (length > 1) {
            format = "%{public}s:" + "%{public}s,".repeat(length - 1).slice(0, -1);
        }
        for (let index = 0; index < args.length; index++) {
            const arg = args[index];
            if (arg === null) {
                arr.push("null");
            }
            else if (typeof arg === 'object') {
                let i8 = this.prettyJson ? "\n" : "";
                arr.push(i8 + JSON.stringify(arg, null, this.prettyJson ? "\t" : undefined) + i8);
            }
            else {
                arr.push(`${arg}`);
            }
        }
        return format;
    }
}
