import * as __WEBPACK_EXTERNAL_MODULE_lodash__ from "lodash";
import * as __WEBPACK_EXTERNAL_MODULE__variables_utils_isVariable_mjs__ from "../../../variables/utils/isVariable.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__variables_utils_transformVariableValue_mjs__ from "../../../variables/utils/transformVariableValue.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__logic_mjs__ from "./logic.mjs";
const parseVariables = (str, ctx)=>{
    var _str_match;
    const regex = /{{(.*?)}}/;
    const matches = null == str ? void 0 : null === (_str_match = str.match) || void 0 === _str_match ? void 0 : _str_match.call(str, regex);
    if (!matches) return str;
    {
        const result = __WEBPACK_EXTERNAL_MODULE_lodash__["default"].get(ctx, matches[1]);
        return __WEBPACK_EXTERNAL_MODULE_lodash__["default"].isFunction(result) ? result() : result;
    }
};
function getInnermostKeyAndValue(obj) {
    if ('object' != typeof obj || null === obj) return null;
    for(const key in obj)if (Object.prototype.hasOwnProperty.call(obj, key)) {
        if ('[object Object]' === Object.prototype.toString.call(obj[key]) && null !== obj[key]) return getInnermostKeyAndValue(obj[key]);
        return {
            key,
            value: obj[key]
        };
    }
    return null;
}
const getTargetField = (obj)=>{
    const keys = getAllKeys(obj);
    const index = (0, __WEBPACK_EXTERNAL_MODULE_lodash__.findIndex)(keys, (key, index, keys)=>{
        if (key.includes('$') && index > 0) return true;
    });
    const result = keys.slice(0, index);
    return result;
};
function getAllKeys(obj) {
    const keys = [];
    function traverse(o) {
        Object.keys(o).sort().forEach(function(key) {
            keys.push(key);
            if (o[key] && 'object' == typeof o[key]) traverse(o[key]);
        });
    }
    traverse(obj);
    return keys;
}
const conditionAnalyses = async (param)=>{
    let { ruleGroup, variables, localVariables } = param;
    const type = Object.keys(ruleGroup)[0] || '$and';
    const conditions = ruleGroup[type];
    let results = [];
    for (const condition of conditions){
        if ('$and' in condition || '$or' in condition) return await conditionAnalyses({
            ruleGroup: condition,
            variables,
            localVariables
        });
        const jsonlogic = getInnermostKeyAndValue(condition);
        const operator = null == jsonlogic ? void 0 : jsonlogic.key;
        if (!operator) return true;
        const targetFieldArr = getTargetField(condition);
        const targetVariableName = targetFieldToVariableString(targetFieldArr);
        const localFormRecord = localVariables.find((v)=>'$nForm' === v.name);
        if (null == localFormRecord ? void 0 : localFormRecord.ctx) {
            const targetValue = __WEBPACK_EXTERNAL_MODULE_lodash__["default"].get(localFormRecord.ctx, targetFieldArr);
            const targetCollectionField = await variables.getCollectionField(targetVariableName, localVariables);
            const result = (0, __WEBPACK_EXTERNAL_MODULE__logic_mjs__.getJsonLogic)().apply({
                [operator]: [
                    (0, __WEBPACK_EXTERNAL_MODULE__variables_utils_transformVariableValue_mjs__.transformVariableValue)(targetValue, {
                        targetCollectionField
                    }),
                    (0, __WEBPACK_EXTERNAL_MODULE__variables_utils_transformVariableValue_mjs__.transformVariableValue)(jsonlogic.value, {
                        targetCollectionField
                    })
                ]
            });
            results.push(result);
            continue;
        }
        const targetValue = variables.parseVariable(targetVariableName, localVariables);
        const parsingResult = (0, __WEBPACK_EXTERNAL_MODULE__variables_utils_isVariable_mjs__.isVariable)(null == jsonlogic ? void 0 : jsonlogic.value) ? [
            variables.parseVariable(null == jsonlogic ? void 0 : jsonlogic.value, localVariables),
            targetValue
        ] : [
            null == jsonlogic ? void 0 : jsonlogic.value,
            targetValue
        ];
        try {
            const jsonLogic = (0, __WEBPACK_EXTERNAL_MODULE__logic_mjs__.getJsonLogic)();
            const [value, targetValue] = await Promise.all(parsingResult);
            const targetCollectionField = await variables.getCollectionField(targetVariableName, localVariables);
            const result = jsonLogic.apply({
                [operator]: [
                    (0, __WEBPACK_EXTERNAL_MODULE__variables_utils_transformVariableValue_mjs__.transformVariableValue)(targetValue, {
                        targetCollectionField
                    }),
                    (0, __WEBPACK_EXTERNAL_MODULE__variables_utils_transformVariableValue_mjs__.transformVariableValue)(value, {
                        targetCollectionField
                    })
                ]
            });
            results.push(result);
        } catch (error) {
            throw error;
        }
    }
    if ('$and' === type) return (0, __WEBPACK_EXTERNAL_MODULE_lodash__.every)(results, (v)=>v);
    return (0, __WEBPACK_EXTERNAL_MODULE_lodash__.some)(results, (v)=>v);
};
function targetFieldToVariableString(targetField) {
    return "{{ $nForm.".concat(targetField.join('.'), " }}");
}
export { conditionAnalyses, getInnermostKeyAndValue, getTargetField, parseVariables, targetFieldToVariableString };
