"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.firstGlobalComponentPromise = exports.awaitGlobalComponent = exports.listenGlobalComponent = exports.getGlobalComponent = void 0;
const NOOP_1 = require("../NOOP");
function getGlobalComponent(system, id) {
    const { global: { component: _component }, } = system;
    const component = _component[id];
    return component;
}
exports.getGlobalComponent = getGlobalComponent;
function listenGlobalComponent(system, id, callback) {
    const { emitter } = system;
    const listener = (component) => {
        callback(component);
    };
    emitter.addListener(id, listener);
    return () => {
        emitter.removeListener(id, listener);
    };
}
exports.listenGlobalComponent = listenGlobalComponent;
function awaitGlobalComponent(system, id, callback) {
    const { emitter } = system;
    const component = getGlobalComponent(system, id);
    if (component) {
        callback(component);
        return NOOP_1.NOOP;
    }
    const listener = (component) => {
        callback(component);
    };
    emitter.addListener(id, listener);
    const unlisten = () => {
        emitter.removeListener(id, listener);
    };
    return unlisten;
}
exports.awaitGlobalComponent = awaitGlobalComponent;
function firstGlobalComponentPromise(system, id) {
    const { emitter } = system;
    const component = system.getLocalComponents(id)[0];
    if (component) {
        return Promise.resolve(component);
    }
    return new Promise((resolve) => {
        const listener = (component) => {
            setTimeout(() => {
                emitter.removeListener(id, listener);
            }, 0);
            resolve(component);
        };
        emitter.addListener(id, listener);
    });
}
exports.firstGlobalComponentPromise = firstGlobalComponentPromise;
//# sourceMappingURL=globalComponent.js.map