"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.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (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("@debug-server-next/utils/log");
const app_client_1 = require("./app-client");
const log = new log_1.Logger('app-client:tunnel');
/**
 * Communicate with app by TCP, implement by Tunnel.node
 */
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 doesn't support multiple debug instance, so remove last listeners
        tunnelEmitter.removeAllListeners(TUNNEL_EVENT);
        tunnelEmitter.on(TUNNEL_EVENT, async (data) => {
            let msgObject;
            try {
                msgObject = JSON.parse(data);
            }
            catch (e) {
                return log.error('parse tunnel response json failed. error: %s, \n msg: %j', e === null || e === void 0 ? void 0 : e.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;
