"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.tdfLogMiddleWareManager = void 0;
const tslib_1 = require("tslib");
const enum_tdf_mapping_1 = require("tdf-devtools-protocol/dist/types/enum-tdf-mapping");
const safe_1 = require("colors/safe");
const enum_chrome_mapping_1 = require("tdf-devtools-protocol/dist/types/enum-chrome-mapping");
const log_1 = require("@/utils/log");
const log = new log_1.Logger('tdf-log-middleware');
exports.tdfLogMiddleWareManager = {
    downwardMiddleWareListMap: {
        [enum_tdf_mapping_1.TdfEvent.TDFLogGetLog]: ({ msg, sendToDevtools }) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
            var _a;
            const eventRes = msg;
            const { params } = eventRes;
            try {
                let firstLog;
                yield Promise.all(params.log.map((log) => {
                    const event = {
                        method: enum_chrome_mapping_1.ChromeEvent.LogEntryAdded,
                        params: {
                            entry: convertTDFLogToChromeLog(log),
                        },
                    };
                    firstLog !== null && firstLog !== void 0 ? firstLog : (firstLog = event);
                    return sendToDevtools(event);
                }));
                return firstLog;
            }
            catch (e) {
                log.error(`${enum_chrome_mapping_1.ChromeEvent.LogEntryAdded} failed! %s`, (_a = e) === null || _a === void 0 ? void 0 : _a.stack);
                return Promise.reject(e);
            }
        }),
    },
    upwardMiddleWareListMap: {},
};
const convertTDFLogToChromeLog = (log) => {
    // app 端回包单位为纳秒，需换算为毫秒， 1 毫秒 = 1000000 纳秒
    const timestamp = `${new Date(Math.floor(log.timestamp / 1000000)).toLocaleString()}(${log.timestamp})`;
    const logPrefixTemp = `[${timestamp}] [${log.level}] [${log.source}] `;
    const logPrefix = log.module ? `${logPrefixTemp}[${log.module}] ` : `${logPrefixTemp}`;
    const consoleMessage = {
        // 脚本生成的类型声明使用了联合类型，为了方便处理直接转为 any
        source: 'other',
        level: 'info',
        text: `${safe_1.blue(logPrefix)}${safe_1.black(log.message)}`,
        lineNumber: log.line_number,
        timestamp: Date.now(),
        url: log.file_name,
    };
    return consoleMessage;
};
