import React, { useContext, useEffect, useMemo, useState } from "react";
import { useEndpoint } from "@strata-foundation/react";
export const VariablesContext = React.createContext({
    variables: null,
    setVariables: (i) => null,
    register: () => null,
    execWithDeps: () => Promise.resolve(),
});
//@ts-ignore
export const VariablesProvider = ({ children }) => {
    const [variables, setVariables] = useState(null);
    const [dependencies, setDependencies] = useState({});
    const [executed, setExecuted] = useState(new Set());
    const register = (name, deps, exec) => {
        setDependencies((d) => ({
            ...d,
            [name]: { deps, exec },
        }));
    };
    const execWithDeps = useMemo(() => async (name, vars = variables) => {
        for (const dep of dependencies[name].deps) {
            if (!executed.has(dep)) {
                vars = { ...vars, ...(await execWithDeps(dep, vars)) };
            }
        }
        const ret = await dependencies[name].exec(vars);
        setExecuted((e) => {
            e.add(name);
            return e;
        });
        setVariables(ret);
        return ret;
    }, [dependencies, setVariables, variables]);
    const { cluster } = useEndpoint();
    useEffect(() => {
        setVariables(vars => ({
            ...vars,
            cluster
        }));
    }, [cluster]);
    return (React.createElement(VariablesContext.Provider, { value: { variables, setVariables, register, execWithDeps } }, children));
};
export const useVariablesContext = () => {
    return useContext(VariablesContext);
};
export const useVariables = () => {
    return useVariablesContext().variables || {};
};
//# sourceMappingURL=variables.js.map