"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TunnelAppClient = void 0;
const log_1 = require("@/utils/log");
const app_client_1 = require("./app-client");
const log = new log_1.Logger('app-client:tunnel');
class TunnelAppClient extends app_client_1.AppClient {
    constructor(id, option) {
        var _a;
        super(id, option);
        this.requestPromiseMap = new Map();
        if (typeof ((_a = global.addon) === null || _a === void 0 ? void 0 : _a.sendMsg) === 'undefined') {
            throw new Error('tunnel does not imported.');
        }
        this.registerMessageListener();
    }
    async registerMessageListener() {
        const { tunnelEmitter, TUNNEL_EVENT } = await Promise.resolve().then(() => __importStar(require('../child-process/index')));
        // TODO tunnel 暂不支持多调试实例，这里暂时移除上一个实例的事件监听
        tunnelEmitter.removeAllListeners(TUNNEL_EVENT);
        tunnelEmitter.on(TUNNEL_EVENT, async (data) => {
            var _a;
            let msgObject;
            try {
                msgObject = JSON.parse(data);
            }
            catch (e) {
                return log.error('parse tunnel response json failed. error: %s, \n msg: %j', (_a = e) === null || _a === void 0 ? void 0 : _a.stack, data);
            }
            if ('id' in msgObject) {
                const requestPromise = this.requestPromiseMap.get(msgObject.id);
                if (requestPromise)
                    requestPromise.resolve(msgObject);
            }
            const res = await this.downwardMessageHandler(msgObject);
            if (!('id' in msgObject))
                return;
            const requestPromise = this.requestPromiseMap.get(msgObject.id);
            if (requestPromise) {
                requestPromise.resolve(res);
            }
        });
    }
    sendHandler(msg) {
        return new Promise((resolve, reject) => {
            if (msg.id) {
                this.requestPromiseMap.set(msg.id, { resolve, reject });
            }
            global.addon.sendMsg(JSON.stringify(msg));
        });
    }
}
exports.TunnelAppClient = TunnelAppClient;
