"use strict";
var __webpack_require__ = {};
(()=>{
    __webpack_require__.n = function(module) {
        var getter = module && module.__esModule ? function() {
            return module['default'];
        } : function() {
            return module;
        };
        __webpack_require__.d(getter, {
            a: getter
        });
        return getter;
    };
})();
(()=>{
    __webpack_require__.d = function(exports1, definition) {
        for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
            enumerable: true,
            get: definition[key]
        });
    };
})();
(()=>{
    __webpack_require__.o = function(obj, prop) {
        return Object.prototype.hasOwnProperty.call(obj, prop);
    };
})();
(()=>{
    __webpack_require__.r = function(exports1) {
        if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
            value: 'Module'
        });
        Object.defineProperty(exports1, '__esModule', {
            value: true
        });
    };
})();
var __webpack_exports__ = {};
__webpack_require__.r(__webpack_exports__);
__webpack_require__.d(__webpack_exports__, {
    VariablesContext: ()=>VariablesContext,
    default: ()=>VariablesProvider_rslib_entry_
});
const jsx_runtime_namespaceObject = require("react/jsx-runtime");
const external_react_namespaceObject = require("react");
const schema_namespaceObject = require("@tachybase/schema");
const client_namespaceObject = require("@tachybase/utils/client");
const external_lodash_namespaceObject = require("lodash");
var external_lodash_default = /*#__PURE__*/ __webpack_require__.n(external_lodash_namespaceObject);
const index_js_namespaceObject = require("../api-client/index.js");
const external_collection_manager_index_js_namespaceObject = require("../collection-manager/index.js");
const external_schema_component_index_js_namespaceObject = require("../schema-component/index.js");
const useBuiltinVariables_js_namespaceObject = require("./hooks/useBuiltinVariables.js");
var useBuiltinVariables_js_default = /*#__PURE__*/ __webpack_require__.n(useBuiltinVariables_js_namespaceObject);
const filterEmptyValues_js_namespaceObject = require("./utils/filterEmptyValues.js");
const getAction_js_namespaceObject = require("./utils/getAction.js");
const getPath_js_namespaceObject = require("./utils/getPath.js");
const hasRequested_js_namespaceObject = require("./utils/hasRequested.js");
const isVariable_js_namespaceObject = require("./utils/isVariable.js");
const uniq_js_namespaceObject = require("./utils/uniq.js");
const VariablesContext = /*#__PURE__*/ (0, external_react_namespaceObject.createContext)(null);
VariablesContext.displayName = 'VariablesContext';
const VariablesProvider_rslib_entry_variableToCollectionName = {};
const getFieldPath = (variablePath, variableToCollectionName)=>{
    const list = variablePath.split('.');
    const result = list.map((item)=>{
        if (variableToCollectionName[item]) return variableToCollectionName[item];
        return item;
    });
    return result.join('.');
};
const VariablesProvider = (param)=>{
    let { children } = param;
    const ctxRef = (0, external_react_namespaceObject.useRef)({});
    const api = (0, index_js_namespaceObject.useAPIClient)();
    const { getCollectionJoinField } = (0, external_collection_manager_index_js_namespaceObject.useCollectionManager_deprecated)();
    const compile = (0, external_schema_component_index_js_namespaceObject.useCompile)();
    const { builtinVariables } = useBuiltinVariables_js_default()();
    const setCtx = (0, external_react_namespaceObject.useCallback)((ctx)=>{
        if (external_lodash_default().isFunction(ctx)) ctxRef.current = ctx(ctxRef.current);
        else ctxRef.current = ctx;
    }, []);
    const getValue = (0, external_react_namespaceObject.useCallback)(async (variablePath, localVariables, options)=>{
        const list = variablePath.split('.');
        const variableName = list[0];
        const _variableToCollectionName = mergeVariableToCollectionNameWithLocalVariables(VariablesProvider_rslib_entry_variableToCollectionName, localVariables);
        let current = mergeCtxWithLocalVariables(ctxRef.current, localVariables);
        let collectionName = getFieldPath(variableName, _variableToCollectionName);
        if (!(variableName in current)) throw new Error("VariablesProvider: ".concat(variableName, " is not found"));
        for(let index = 0; index < list.length; index++){
            if (null == current) return current;
            if ('$nParentRecord' === list[index]) {
                if (!(list[index + 1] in current[list[index]]) && '__parent' in current[list[index]]) list.splice(1, 0, '__parent');
            }
            const key = list[index];
            const associationField = getCollectionJoinField(getFieldPath(list.slice(0, index + 1).join('.'), _variableToCollectionName));
            if (Array.isArray(current)) {
                const result = current.map((item)=>{
                    if (shouldToRequest(null == item ? void 0 : item[key]) && (null == item ? void 0 : item.id) != null) {
                        if (null == associationField ? void 0 : associationField.target) {
                            const url = "/".concat(collectionName, "/").concat(item.id, "/").concat(key, ":").concat((0, getAction_js_namespaceObject.getAction)(associationField.type));
                            if ((0, hasRequested_js_namespaceObject.hasRequested)(url)) return (0, hasRequested_js_namespaceObject.getRequested)(url);
                            const result = api.request({
                                url,
                                params: {
                                    appends: null == options ? void 0 : options.appends
                                }
                            }).then((data)=>{
                                (0, hasRequested_js_namespaceObject.clearRequested)(url);
                                item[key] = data.data.data;
                                return item[key];
                            });
                            (0, hasRequested_js_namespaceObject.stashRequested)(url, result);
                            return result;
                        }
                    }
                    return null == item ? void 0 : item[key];
                });
                current = external_lodash_default().flatten(await Promise.all(result));
            } else if (shouldToRequest(current[key]) && null != current.id && (null == associationField ? void 0 : associationField.target) && (null == associationField ? void 0 : associationField.type) != 'virtual') {
                const url = "/".concat(collectionName, "/").concat(current.id, "/").concat(key, ":").concat((0, getAction_js_namespaceObject.getAction)(associationField.type));
                let data = null;
                if ((0, hasRequested_js_namespaceObject.hasRequested)(url)) data = await (0, hasRequested_js_namespaceObject.getRequested)(url);
                else {
                    const waitForData = api.request({
                        url,
                        params: {
                            appends: null == options ? void 0 : options.appends
                        }
                    });
                    (0, hasRequested_js_namespaceObject.stashRequested)(url, waitForData);
                    data = await waitForData;
                    (0, hasRequested_js_namespaceObject.clearRequested)(url);
                }
                if (!(0, schema_namespaceObject.raw)(current)[key]) (0, schema_namespaceObject.raw)(current)[key] = data.data.data;
                current = (0, client_namespaceObject.getValuesByPath)(current, key);
            } else current = (0, client_namespaceObject.getValuesByPath)(current, key);
            if (null == associationField ? void 0 : associationField.target) collectionName = associationField.target;
        }
        return compile(external_lodash_default().isFunction(current) ? current() : current);
    }, [
        getCollectionJoinField
    ]);
    const registerVariable = (0, external_react_namespaceObject.useCallback)((variableOption)=>{
        if (!(0, isVariable_js_namespaceObject.isVariable)("{{".concat(variableOption.name, "}}"))) throw new Error("VariablesProvider: ".concat(variableOption.name, " is not a valid name"));
        setCtx((prev)=>({
                ...prev,
                [variableOption.name]: variableOption.ctx
            }));
        if (variableOption.collectionName) VariablesProvider_rslib_entry_variableToCollectionName[variableOption.name] = variableOption.collectionName;
    }, [
        setCtx
    ]);
    const getVariable = (0, external_react_namespaceObject.useCallback)((variableName)=>{
        if (!ctxRef.current[variableName]) return null;
        return {
            name: variableName,
            ctx: ctxRef.current[variableName],
            collectionName: VariablesProvider_rslib_entry_variableToCollectionName[variableName]
        };
    }, []);
    const removeVariable = (0, external_react_namespaceObject.useCallback)((variableName)=>{
        setCtx((prev)=>{
            const next = {
                ...prev
            };
            delete next[variableName];
            return next;
        });
        delete VariablesProvider_rslib_entry_variableToCollectionName[variableName];
    }, [
        setCtx
    ]);
    const parseVariable = (0, external_react_namespaceObject.useCallback)(async (str, localVariables, options)=>{
        if (!(0, isVariable_js_namespaceObject.isVariable)(str)) return str;
        if (localVariables) localVariables = external_lodash_default().isArray(localVariables) ? localVariables : [
            localVariables
        ];
        const path = (0, getPath_js_namespaceObject.getPath)(str);
        const value = await getValue(path, localVariables, options);
        return (0, uniq_js_namespaceObject.uniq)((0, filterEmptyValues_js_namespaceObject.filterEmptyValues)(value));
    }, [
        getValue
    ]);
    const getCollectionField = (0, external_react_namespaceObject.useCallback)(async (variableString, localVariables)=>{
        if (!(0, isVariable_js_namespaceObject.isVariable)(variableString)) throw new Error("VariablesProvider: ".concat(variableString, " is not a variable string"));
        if (localVariables) localVariables = external_lodash_default().isArray(localVariables) ? localVariables : [
            localVariables
        ];
        const path = (0, getPath_js_namespaceObject.getPath)(variableString);
        let result = getCollectionJoinField(getFieldPath(path, mergeVariableToCollectionNameWithLocalVariables(VariablesProvider_rslib_entry_variableToCollectionName, localVariables)));
        if (!result && !path.includes('.')) result = {
            target: VariablesProvider_rslib_entry_variableToCollectionName[path]
        };
        return result;
    }, [
        getCollectionJoinField
    ]);
    (0, external_react_namespaceObject.useEffect)(()=>{
        builtinVariables.forEach((variableOption)=>{
            registerVariable(variableOption);
        });
    }, [
        builtinVariables,
        registerVariable
    ]);
    const value = (0, external_react_namespaceObject.useMemo)(()=>({
            ctxRef,
            setCtx,
            parseVariable,
            registerVariable,
            getVariable,
            getCollectionField,
            removeVariable
        }), [
        getCollectionField,
        getVariable,
        parseVariable,
        registerVariable,
        removeVariable,
        setCtx
    ]);
    return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(VariablesContext.Provider, {
        value: value,
        children: children
    });
};
VariablesProvider.displayName = 'VariablesProvider';
const VariablesProvider_rslib_entry_ = VariablesProvider;
function shouldToRequest(value) {
    let result = false;
    (0, schema_namespaceObject.untracked)(()=>{
        if ('[{}]' === JSON.stringify(value) || '{}' === JSON.stringify(value)) {
            result = true;
            return;
        }
        result = external_lodash_default().isEmpty(value);
    });
    return result;
}
function mergeCtxWithLocalVariables(ctx, localVariables) {
    ctx = {
        ...ctx
    };
    null == localVariables || localVariables.forEach((item)=>{
        ctx[item.name] = item.ctx;
    });
    return ctx;
}
function mergeVariableToCollectionNameWithLocalVariables(variableToCollectionName, localVariables) {
    variableToCollectionName = {
        ...variableToCollectionName
    };
    null == localVariables || localVariables.forEach((item)=>{
        if (item.collectionName) variableToCollectionName[item.name] = item.collectionName;
    });
    return variableToCollectionName;
}
var __webpack_export_target__ = exports;
for(var __webpack_i__ in __webpack_exports__)__webpack_export_target__[__webpack_i__] = __webpack_exports__[__webpack_i__];
if (__webpack_exports__.__esModule) Object.defineProperty(__webpack_export_target__, '__esModule', {
    value: true
});
