import { jsx as _jsx } from "react/jsx-runtime";
import { useMemo } from "react";
import { createContext, useContext, useEffect, useRef, } from "react";
import useEvents from "../hooks/utility/useEvents";
const AsyncProcessContext = createContext(null);
/** Provides the async process functionality to the application */
export default function AsyncProcessProvider({ children, triggers, persistence, }) {
    const { subscriber, dispatcher } = useEvents();
    const wrappedFunctions = useMemo(() => {
        return Object.keys(triggers).reduce((r, k) => ({
            ...r,
            [k]: (...args) => {
                let persisted = persistence.write(k, ...args);
                return triggers[k](...args).finally(() => {
                    persistence.remove(persisted);
                    dispatcher(k);
                });
            },
        }), {});
    }, []);
    useEffect(() => {
        const recoveries = persistence.recover();
        for (let [recoveryId, recoveryProcess] of recoveries)
            recoveryProcess.finally(() => {
                persistence.remove(recoveryId);
            });
    }, []);
    return (_jsx(AsyncProcessContext.Provider, { value: { _subscriber: subscriber, _wrappedFunctions: wrappedFunctions }, children: children }));
}
/** Allows components to use the async process functionality */
export function useAsyncProcess() {
    const { _subscriber: subscriber, _wrappedFunctions } = useContext(AsyncProcessContext);
    const subscriptions = useRef([]);
    useEffect(() => () => {
        for (let unsubscribe of subscriptions.current)
            unsubscribe();
    }, []);
    return {
        on: (k, whatToDo) => {
            subscriptions.current.push(subscriber(k, whatToDo));
        },
        ..._wrappedFunctions,
    };
}
//# sourceMappingURL=AsyncProcess.js.map