import { useEffect, useState } from "react";
import { reaction } from "@tachybase/schema";
import { flatten, getValuesByPath } from "@tego/client";
import lodash from "lodash";
import { mergeFilter } from "../../../../filter-provider/index.mjs";
import { useParseDataScopeFilter } from "../../../../schema-settings/index.mjs";
import { DEBOUNCE_WAIT, isVariable } from "../../../../variables/index.mjs";
import { getPath } from "../../../../variables/utils/getPath.mjs";
import { getVariableName } from "../../../../variables/utils/getVariableName.mjs";
const useFieldServiceFilter = (filter, originalFilter)=>{
    const [fieldServiceFilter, setFieldServiceFilter] = useState(null);
    const { parseFilter, findVariable } = useParseDataScopeFilter();
    useEffect(()=>{
        const filterFromSchema = filter;
        const _run = async ()=>{
            const result = await parseFilter(mergeFilter([
                filterFromSchema || originalFilter
            ]));
            setFieldServiceFilter(result);
        };
        const run = lodash.debounce(_run, DEBOUNCE_WAIT);
        _run();
        const dispose = reaction(()=>{
            const flat = flatten(filterFromSchema, {
                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);
        return dispose;
    }, [
        filter,
        findVariable,
        originalFilter,
        parseFilter
    ]);
    return [
        fieldServiceFilter,
        setFieldServiceFilter
    ];
};
export { useFieldServiceFilter };
