import { useCallback } from "react";
import { flatten, unflatten } from "@tachybase/utils/client";
import { useLocalVariables, useVariables } from "../../variables/index.mjs";
import { getVariableName } from "../../variables/utils/getVariableName.mjs";
import { isVariable } from "../../variables/utils/isVariable.mjs";
const defaultExclude = [
    '$user',
    '$date',
    '$nDate',
    '$nRole'
];
const useParseDataScopeFilter = function() {
    let { exclude = defaultExclude } = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};
    const localVariables = useLocalVariables();
    const variables = useVariables();
    const findVariable = useCallback((name)=>{
        let result = null == variables ? void 0 : variables.getVariable(name);
        if (!result) result = localVariables.find((item)=>item.name === name);
        return result;
    }, [
        localVariables,
        variables
    ]);
    const parseFilter = useCallback(async (filterValue)=>{
        const flat = flatten(filterValue, {
            breakOn (param) {
                let { key } = param;
                return key.startsWith('$') && '$and' !== key && '$or' !== key;
            },
            transformValue (value) {
                if (!isVariable(value)) return value;
                if (exclude.includes(getVariableName(value))) return value;
                const result = null == variables ? void 0 : variables.parseVariable(value, localVariables);
                return result;
            }
        });
        await Promise.all(Object.keys(flat).map(async (key)=>{
            flat[key] = await flat[key];
            if (void 0 === flat[key]) flat[key] = null;
            return flat[key];
        }));
        const result = unflatten(flat);
        return result;
    }, [
        exclude,
        localVariables,
        null == variables ? void 0 : variables.parseVariable
    ]);
    return {
        parseFilter,
        findVariable
    };
};
export { useParseDataScopeFilter };
