"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.listenCustom = exports.makeCustomListener = void 0;
const __1 = require("..");
const callAll_1 = require("../../../util/call/callAll");
const stopPropagation_1 = require("../../stopPropagation");
function makeCustomListener(type, listener, global = false) {
    return (component) => {
        return listenCustom(type, component, listener, global);
    };
}
exports.makeCustomListener = makeCustomListener;
function listenCustom(type, component, listener, global = false) {
    const { $system, $element, $listenCount } = component;
    const _type = `_${type}`;
    const { customEvent, context } = $system;
    if (!customEvent.has(type)) {
        for (const c of context) {
            (0, stopPropagation_1.stopByPropagation)(c.$element, _type);
        }
        customEvent.add(type);
    }
    $listenCount[type] = $listenCount[type] || 0;
    $listenCount[type]++;
    const _listener = (_event) => {
        const { detail } = _event;
        listener(detail, _event);
    };
    const elements = Array.isArray($element) ? $element : [$element];
    const unlisten = (0, callAll_1.callAll)(elements.map((element) => (0, __1._addEventListener)(_type, element, _listener, global)));
    return () => {
        $listenCount[type]--;
        if ($listenCount[type] === 0) {
            delete $listenCount[type];
        }
        unlisten();
    };
}
exports.listenCustom = listenCustom;
//# sourceMappingURL=index.js.map