"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExtHostConnection = void 0;
const ide_core_common_1 = require("@opensumi/ide-core-common");
const vscode_1 = require("../../../common/vscode");
class ExtHostConnection {
    constructor(rpcProtocol) {
        this.rpcProtocol = rpcProtocol;
        this.connections = new Map();
        this.debug = (0, ide_core_common_1.getDebugLogger)();
        this.proxy = rpcProtocol.getProxy(vscode_1.MainThreadAPIIdentifier.MainThreadConnection);
    }
    /**
     * 通过ID获取Connection并发送消息
     * @param id
     * @param message
     */
    async $sendMessage(id, message) {
        var _a;
        if (this.connections.has(id)) {
            (_a = this.connections.get(id)) === null || _a === void 0 ? void 0 : _a.readMessage(message);
        }
    }
    /**
     * 创建Connection
     * @param id
     */
    async $createConnection(id) {
        await this.doEnsureConnection(id);
    }
    /**
     * 移除Connection
     * @param id
     */
    async $deleteConnection(id) {
        this.connections.delete(id);
    }
    /**
     * 如果已存在，返回存在的Connection，否则创建新的Connection
     * @param id
     */
    async ensureConnection(id) {
        const connection = await this.doEnsureConnection(id);
        this.proxy.$createConnection(id);
        return connection;
    }
    /**
     * 如果已存在，返回存在的Connection，否则创建新的Connection
     * @param id
     */
    async doEnsureConnection(id) {
        const connection = this.connections.get(id) || (await this.doCreateConnection(id));
        this.connections.set(id, connection);
        return connection;
    }
    /**
     * 创建新的Connection
     * @param id
     */
    async doCreateConnection(id) {
        return new vscode_1.ExtensionConnection(id, this.proxy, () => {
            this.connections.delete(id);
            this.proxy.$deleteConnection(id);
        });
    }
}
exports.ExtHostConnection = ExtHostConnection;
//# sourceMappingURL=ext.host.connection.js.map