import { useState } from "react";
import { reaction } from "@tachybase/schema";
import { flatten, getValuesByPath } from "@tego/client";
import { useDeepCompareEffect } from "ahooks";
import lodash from "lodash";
import { useParseDataScopeFilter } from "../../schema-settings/index.mjs";
import { DEBOUNCE_WAIT } from "../../variables/index.mjs";
import { getPath } from "../../variables/utils/getPath.mjs";
import { getVariableName } from "../../variables/utils/getVariableName.mjs";
import { isVariable } from "../../variables/utils/isVariable.mjs";
function useParsedFilter(param) {
    let { filterOption } = param;
    const { parseFilter, findVariable } = useParseDataScopeFilter();
    const [filter, setFilter] = useState({});
    useDeepCompareEffect(()=>{
        if (!filterOption) return;
        const _run = async ()=>{
            const result = await parseFilter(filterOption);
            setFilter(result);
        };
        _run();
        const run = lodash.debounce(_run, DEBOUNCE_WAIT);
        reaction(()=>{
            const flat = flatten(filterOption, {
                breakOn (param) {
                    let { key } = param;
                    return key.startsWith('$') && '$and' !== key && '$or' !== key;
                },
                transformValue (value) {
                    if (!isVariable(value)) return value;
                    const variableName = getVariableName(value);
                    const variable = findVariable(variableName);
                    const result = getValuesByPath({
                        [variableName]: (null == variable ? void 0 : variable.ctx) || {}
                    }, getPath(value));
                    return result;
                }
            });
            return flat;
        }, run);
    }, [
        filterOption
    ]);
    return {
        filter
    };
}
export { useParsedFilter };
