import { useRef } from "react";
import { createSimpleContext } from "../simple";
const useEventDispatcherHook = () => {
    const receivers = useRef({});
    const subscribe = (eventName, cb) => {
        let recvs = receivers.current[eventName];
        if (!recvs) {
            receivers.current[eventName] = [];
        }
        receivers.current[eventName].push(cb);
        recvs = receivers.current[eventName];
        const currEmitter = recvs[recvs.length - 1];
        return () => {
            receivers.current[eventName] = receivers.current[eventName]
                .filter(r => r !== currEmitter);
        };
    };
    const dispatch = (eventName, args) => {
        if (!receivers.current[eventName]) {
            throw `Event named "${eventName}" isn't subscribed yet`;
        }
        receivers.current[eventName].forEach(r => r(args));
    };
    return {
        subscribe,
        dispatch,
    };
};
const Context = createSimpleContext("event-dispatcher", {
    subscribe: (_1, _2) => {
        throw "Not implemented";
    },
    dispatch: (_1, _2) => {
        throw "Not implemented";
    },
}, useEventDispatcherHook);
export const EventDispatcherProvider = Context.Provider;
export const useEventDispatcher = Context.useContext;
//# sourceMappingURL=index.js.map