"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WSAppClient = void 0;
const tslib_1 = require("tslib");
const ws_1 = tslib_1.__importDefault(require("ws"));
const log_1 = require("@/utils/log");
const app_client_1 = require("./app-client");
const log = new log_1.Logger('app-client:ws');
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();
    }
    registerMessageListener() {
        this.ws.on('message', (msg) => tslib_1.__awaiter(this, void 0, void 0, function* () {
            let msgObj;
            try {
                msgObj = JSON.parse(msg);
            }
            catch (e) {
                log.error(`parse WSAppClient json message error: ${msg}`);
            }
            const res = yield 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.isClosed = true;
            log.info(`${this.id} WSAppClient closed.`);
            this.emit("close" /* 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;
