export default class Log {
    private static logs = '';
    private static counter = { info: 0, error: 0, warning: 0 };

    public static info(...o): void {
        Log.counter.info++;
        let flag = '%c WH %cIFO%c' + this.getTime() + '%c';
        if (this.debug()) {
            console.log(flag, 'background:grey;color:white;', '', 'color:grey;', '', ...o);
        }
        this.saveLogs(flag, ...o);
    }

    public static error(...o): void {
        Log.counter.error++;
        let flag = '%c WH %cERR%c' + this.getTime() + '%c';
        console.error(flag, 'background:grey;color:white;', 'background:red;color:white;', 'color:grey;', '', ...o);
        this.saveLogs(flag, ...o);
    }

    public static warn(...o): void {
        Log.counter.warning++;
        let flag = '%c WH %cWRN%c' + this.getTime() + '%c';
        console.warn(flag, 'background:grey;color:white;', 'background:#ff9800;color:white;', 'color:grey;', '', ...o);
        this.saveLogs(flag, ...o);
    }

    public static debug(): boolean {
        let ret: boolean = true;
        try {
            let local = JSON.parse(localStorage.getItem('wh_trans_settings'));
            if (local) ret = local['isDev'];
        } catch {
            this.error('debug错误')
        }
        return ret;
    }

    public static getTime(): string {
        let d = new Date();
        let year = d.getFullYear();
        let month = ('0' + (d.getMonth() + 1)).slice(-2);
        let date = ('0' + d.getDate()).slice(-2);
        let hours = ('0' + d.getHours()).slice(-2);
        let minutes = ('0' + d.getMinutes()).slice(-2);
        let seconds = ('0' + d.getSeconds()).slice(-2);
        let ms = ('00' + d.getMilliseconds()).slice(-3);
        return `${ year }-${ month }-${ date } ${ hours }:${ minutes }:${ seconds }.${ ms }`;
    }

    public static getLogs() {
        return this.logs;
    }

    private static saveLogs(...o) {
        o.forEach(item => {
            if (typeof item === 'string') this.logs += item.replaceAll('%c', '');
            else if (item !== null && item !== undefined) {
                let json = '{}';
                let name = Object.getPrototypeOf(item).constructor.name;
                try {
                    json = JSON.stringify(item);
                } catch {
                }
                this.logs += ` [${ name }] [${ json }] `;
                if (item.message) this.logs += '错误信息: ' + item.message;
                if (item.stack) this.logs += '错误堆栈: ' + item.stack;
            }
        })
        this.logs += '\r\n';
    }

    public static getCounter() {
        return {
            info: Log.counter.info,
            error: Log.counter.error,
            warning: Log.counter.warning,
        }
    }
}
