"use strict";
/*
 * Tencent is pleased to support the open source community by making
 * Hippy available.
 *
 * Copyright (C) 2017-2019 THL A29 Limited, a Tencent company.
 * All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.tdfLogMiddleWareManager = void 0;
const enum_tdf_mapping_1 = require("@hippy/devtools-protocol/dist/types/enum-tdf-mapping");
const safe_1 = require("colors/safe");
const enum_chrome_mapping_1 = require("@hippy/devtools-protocol/dist/types/enum-chrome-mapping");
const log_1 = require("@debug-server-next/utils/log");
const log = new log_1.Logger('tdf-log-middleware');
exports.tdfLogMiddleWareManager = {
    downwardMiddleWareListMap: {
        [enum_tdf_mapping_1.TdfEvent.TDFLogGetLog]: async ({ msg, sendToDevtools }) => {
            const eventRes = msg;
            const { params } = eventRes;
            try {
                let firstLog;
                await 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`, e === null || e === void 0 ? void 0 : e.stack);
                return Promise.reject(e);
            }
        },
    },
    upwardMiddleWareListMap: {},
};
const convertTDFLogToChromeLog = (log) => {
    // 1ms = 1000000ns
    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 = {
        source: 'other',
        level: 'info',
        text: `${(0, safe_1.blue)(logPrefix)}${(0, safe_1.black)(log.message)}`,
        lineNumber: log.line_number,
        timestamp: Date.now(),
        url: log.file_name,
    };
    return consoleMessage;
};
