"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExtHostCommon = void 0;
exports.createEventAPIFactory = createEventAPIFactory;
const ide_core_common_1 = require("@opensumi/ide-core-common");
const common_1 = require("../../../common");
const sumi_1 = require("../../../common/sumi");
class ExtHostCommon {
    constructor(rpcProtocol) {
        this.rpcProtocol = rpcProtocol;
        this.emitters = new Map();
        this.rpcProtocol = rpcProtocol;
        this.proxy = this.rpcProtocol.getProxy(sumi_1.MainThreadSumiAPIIdentifier.MainThreadCommon);
    }
    async $acceptEvent(eventName, eventArgs) {
        if (!this.emitters.has(eventName)) {
            return [];
        }
        const res = await this.emitters.get(eventName).fireAndAwait(eventArgs);
        return res;
    }
    onEvent(eventName, listener) {
        if (!this.emitters.has(eventName)) {
            this.emitters.set(eventName, new ide_core_common_1.Emitter());
        }
        this.proxy.$subscribeEvent(eventName);
        const disposer = this.emitters.get(eventName).event((eventArgs) => listener(...eventArgs));
        return {
            dispose: () => {
                disposer.dispose();
                if (this.emitters.get(eventName).listenerSize === 0) {
                    this.proxy.$unSubscribeEvent(eventName);
                }
            },
        };
    }
}
exports.ExtHostCommon = ExtHostCommon;
function createEventAPIFactory(extHostCommands, kaitianCommon, extension) {
    return {
        fire: async (eventName, ...eventArgs) => await extHostCommands.executeCommand(common_1.EMIT_EXT_HOST_EVENT.id, eventName, ...eventArgs),
        subscribe: (eventName, listener) => kaitianCommon.onEvent(eventName, listener),
    };
}
//# sourceMappingURL=ext.host.common.js.map