import { jsx as _jsx } from "react/jsx-runtime";
import { createContext, useContext, useEffect, useMemo, useState } from 'react';
import { runJinja } from '../python/index.js';
import { JinjaContextValue } from './JinjaContextValue.js';
const context = createContext(undefined);
export function JinjaContext({ children, ...props }) {
    const parent = useContext(context);
    const value = useMemo(() => new JinjaContextValue({ ...props, parent }), [props.name, props.prefix, props.variables]);
    return _jsx(context.Provider, { value: value, children: children });
}
export function JinjaRawContext({ children, value }) {
    return _jsx(context.Provider, { value: value, children: children });
}
export function useJinjaContext(name) {
    const ctx = useContext(context);
    return useMemo(() => {
        let result = ctx;
        while (name && result && result.name !== name) {
            result = result.parent;
        }
        return result;
    }, [ctx, name]);
}
function getVariable(ctx, key, ignore) {
    while (ctx && (ignore?.includes(ctx.name ?? '') || !ctx.has(key)))
        ctx = ctx.parent;
    return ctx?.get(key);
}
export function useJinjaVariable(key, ignore) {
    const ctx = useJinjaContext();
    return useMemo(() => getVariable(ctx, key, ignore), [ctx, ignore?.join(',')]);
}
export function useJinjaVariables(keys, ignore) {
    const ctx = useJinjaContext();
    return useMemo(() => keys.map(key => getVariable(ctx, key, ignore)), [ctx, ignore?.join(',')]);
}
export function useAllJinjaVariables(ignore) {
    const ctx = useJinjaContext();
    return useMemo(() => ctx?.getAll(ignore), [ctx, ignore?.join(',')]);
}
export function useJinjaExpressions(expressions, ignore) {
    const [results, setResults] = useState();
    const variables = useAllJinjaVariables(ignore);
    useEffect(() => {
        (async () => {
            const result = await Promise.all(expressions.map(e => runJinja(e, variables)));
            setResults(result);
        })();
    }, []);
    return results;
}
export function useJinja(expression, ignore) {
    return useJinjaExpressions([expression], ignore)?.[0];
}
//# sourceMappingURL=JinjaContext.js.map