"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.WSAppClient = void 0;
const tslib_1 = require("tslib");
const ws_1 = tslib_1.__importDefault(require("ws"));
const enum_1 = require("@debug-server-next/@types/enum");
const log_1 = require("@debug-server-next/utils/log");
const app_client_1 = require("./app-client");
const log = new log_1.Logger('app-client:ws');
/**
 * Communicate with app by WebSocket
 */
class WSAppClient extends app_client_1.AppClient {
    constructor(id, option) {
        super(id, option);
        this.requestPromiseMap = new Map();
        this.ws = option.ws;
        if (!this.ws) {
            const e = new Error('WSAppClient constructor option need ws');
            throw e;
        }
        this.registerMessageListener();
    }
    destroy() {
        var _a;
        if (((_a = this.ws) === null || _a === void 0 ? void 0 : _a.readyState) === ws_1.default.OPEN)
            this.ws.close(enum_1.WSCode.AppClientDestroyed, 'WSAppClient is destroyed');
    }
    registerMessageListener() {
        this.ws.on('message', async (msg) => {
            const msgStr = msg.toString();
            let msgObj;
            try {
                msgObj = JSON.parse(msgStr);
            }
            catch (e) {
                return log.error(`parse WSAppClient json message error: ${msg}`);
            }
            const res = await this.downwardMessageHandler(msgObj);
            if (!('id' in msgObj))
                return;
            const requestPromise = this.requestPromiseMap.get(msgObj.id);
            if (requestPromise)
                requestPromise.resolve(res);
        });
        this.ws.on('close', () => {
            this.emit("close" /* AppClientEvent.Close */);
        });
    }
    sendHandler(msg) {
        if (this.ws.readyState !== ws_1.default.OPEN)
            return;
        return new Promise((resolve, reject) => {
            const msgStr = JSON.stringify(msg);
            this.ws.send(msgStr);
            this.requestPromiseMap.set(msg.id, { resolve, reject });
        });
    }
}
exports.WSAppClient = WSAppClient;
