"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TunnelAppClient = void 0;
const tslib_1 = require("tslib");
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();
    }
    registerMessageListener() {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const { tunnelEmitter, TUNNEL_EVENT } = yield Promise.resolve().then(() => tslib_1.__importStar(require('../child-process/index')));
            // TODO tunnel 暂不支持多调试实例，这里暂时移除上一个实例的事件监听
            tunnelEmitter.removeAllListeners(TUNNEL_EVENT);
            tunnelEmitter.on(TUNNEL_EVENT, (data) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                var _a;
                let msgObject;
                try {
                    msgObject = JSON.parse(data);
                }
                catch (e) {
                    return log.info('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 = yield 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;
