import { jsx as _jsx } from "react/jsx-runtime";
import { useMemo } from 'react';
import { JinjaContext, useJinjaContext } from '../context/JinjaContext.js';
import { ObservableValue } from '../utils/ObservableValue.js';
import { GeneratedConnectionsProvider } from './ConnectionInterface.js';
const variablesContextName = 'dynamic-form-variables';
const pluginVariablesContextName = 'dynamic-form-plugin-variables';
export const globalVariablesContextName = 'dynamic-form-global-variables';
export function varListToVarObject(vars, source) {
    return vars?.reduce((result, variable) => ({
        ...result,
        [variable.name]: {
            initialValue: variable.value,
            metadata: {
                source,
                description: variable.description,
            },
        },
    }), {});
}
export const VariablesContext = ({ auth, account, workspace, stack, children }) => {
    const accountVars = useMemo(() => varListToVarObject(account, 'account'), [account]);
    const authVars = useMemo(() => varListToVarObject(auth, 'auth'), [auth]);
    const workspaceVars = useMemo(() => varListToVarObject(workspace, 'workspace'), [workspace]);
    const stackVars = useMemo(() => varListToVarObject(stack, 'stack'), [stack]);
    const all = useMemo(() => ({ ...authVars, ...accountVars, ...workspaceVars, ...stackVars }), [account, auth, workspace, stack]);
    return _jsx(JinjaContext, { name: variablesContextName, variables: all, prefix: "var", children: children });
};
export const PluginVariablesContext = ({ variables, children }) => {
    const pluginVars = useMemo(() => varListToVarObject(variables, 'plugin') ?? {}, [variables]);
    return _jsx(JinjaContext, { name: pluginVariablesContextName, variables: pluginVars, prefix: "var", children: children });
};
export const GlobalContext = ({ children }) => {
    const generatedConnections = useMemo(() => new ObservableValue({}), []);
    return (_jsx(GeneratedConnectionsProvider, { value: generatedConnections, children: _jsx(JinjaContext, { name: globalVariablesContextName, variables: {}, children: children }) }));
};
export function useContextVariables() {
    const variablesCtx = useJinjaContext(variablesContextName);
    const pluginVariablesCtx = useJinjaContext(pluginVariablesContextName);
    if (!variablesCtx)
        throw new Error('Dynamic form error: VariablesContext is not defined.');
    if (!pluginVariablesCtx)
        throw new Error('Dynamic form error: PluginVariablesContext is not defined.');
    return { ...variablesCtx.variables, ...pluginVariablesCtx.variables };
}
//# sourceMappingURL=VariablesContext.js.map