import Log from "../Log";
import Popup from "../utils/Popup";
import CommonUtils from "../utils/CommonUtils";
import VIEW_LOGS_HANDLER_HTML from "../../../static/html/view_logs_handler.html";
import ClassName from "../../container/ClassName";
import { Injectable } from "../../container/Injectable";
import Logger from "../Logger";

@ClassName('ViewLogsHandler')
@Injectable()
export default class ViewLogsHandler {

    constructor(
        private readonly commonUtils: CommonUtils,
        private readonly logger: Logger,
    ) {
    }

    public handle(): void {
        let logCounter = this.logger.getCounter();
        let pop = new Popup(VIEW_LOGS_HANDLER_HTML
            .replace('{{}}', logCounter.info.toString())
            .replace('{{}}', logCounter.warning.toString())
            .replace('{{}}', logCounter.error.toString()), '查看日志');
        window.setTimeout(() => {
            let container = pop.element.querySelector('div');
            let text = document.createElement('div');
            let logs = Log.getLogs().split('\r\n');
            logs.forEach(log => {
                let p = document.createElement('p');
                p.innerText = log;
                if (log.slice(0, 10).includes('ERR')) {
                    p.style.backgroundColor = '#ff000080';
                } else if (log.slice(0, 10).includes('WRN')) {
                    p.style.backgroundColor = '#ffff0080';
                }
                text.append(p);
            });
            pop.element.querySelector('button').addEventListener('click', () => window.setTimeout(() => {
                this.commonUtils.exportTextFile(
                    'wuhu_log_' + Log.getTime()
                        .replace('[', '')
                        .replace(']', '')
                        .replace(' ', '')
                        .replace('.', '')
                        .replaceAll('-', '')
                        .replaceAll(':', '') + '.log',
                    [Log.getLogs()]
                );
            }, 0));
            container.innerHTML = '';
            container.append(text);
        }, 0);
    }
}
