import { FieldsUtils } from '../../../services/fields';
var ShowCondition = /** @class */ (function () {
    // Expects a show condition of the form: <fieldName>="string"
    function ShowCondition(condition) {
        this.condition = condition;
    }
    ShowCondition.addPathPrefixToCondition = function (showCondition, pathPrefix) {
        if (!pathPrefix || pathPrefix === '') {
            return showCondition;
        }
        if (showCondition.search(ShowCondition.OR_CONDITION_REGEXP) !== -1) {
            var orConditions = showCondition.split(ShowCondition.OR_CONDITION_REGEXP);
            orConditions = this.extractConditions(orConditions, pathPrefix);
            return orConditions.join(' OR ');
        }
        else {
            var andConditions = showCondition.split(ShowCondition.AND_CONDITION_REGEXP);
            andConditions = this.extractConditions(andConditions, pathPrefix);
            return andConditions.join(' AND ');
        }
    };
    ShowCondition.extractConditions = function (orConditions, pathPrefix) {
        orConditions = orConditions.map(function (condition) {
            if (!condition.startsWith(pathPrefix)) {
                return pathPrefix + '.' + condition;
            }
            else {
                return condition;
            }
        });
        return orConditions;
    };
    ShowCondition.prototype.match = function (fields, path) {
        if (!this.condition) {
            return true;
        }
        return this.matchAndConditions(fields, this.condition, path);
    };
    ShowCondition.prototype.matchAndConditions = function (fields, condition, path) {
        var _this = this;
        if (condition.search(ShowCondition.OR_CONDITION_REGEXP) !== -1) {
            var orConditions = condition.split(ShowCondition.OR_CONDITION_REGEXP);
            return orConditions.some(function (orCondition) { return _this.matchEqualityCondition(fields, orCondition, path); });
        }
        else {
            var andConditions = condition.split(ShowCondition.AND_CONDITION_REGEXP);
            return andConditions.every(function (andCondition) { return _this.matchEqualityCondition(fields, andCondition, path); });
        }
    };
    ShowCondition.prototype.matchEqualityCondition = function (fields, condition, path) {
        if (condition.search(ShowCondition.CONTAINS) === -1) {
            var conditionSeparator = ShowCondition.CONDITION_EQUALS;
            if (condition.indexOf(ShowCondition.CONDITION_NOT_EQUALS) !== -1) {
                conditionSeparator = ShowCondition.CONDITION_NOT_EQUALS;
            }
            var field = condition.split(conditionSeparator)[0];
            var _a = field.split('.'), head = _a[0], tail = _a.slice(1);
            var currentValue = this.findValueForComplexCondition(fields, head, tail, path);
            var expectedValue = this.unquoted(condition.split(conditionSeparator)[1]);
            return this.checkValueEquals(expectedValue, currentValue, conditionSeparator);
        }
        else {
            var field = condition.split(ShowCondition.CONTAINS)[0];
            var _b = field.split('.'), head = _b[0], tail = _b.slice(1);
            var currentValue = this.findValueForComplexCondition(fields, head, tail, path);
            var expectedValue = this.unquoted(condition.split(ShowCondition.CONTAINS)[1]);
            return this.checkValueContains(expectedValue, currentValue);
        }
    };
    ShowCondition.prototype.checkValueEquals = function (expectedValue, currentValue, conditionSeparaor) {
        if (expectedValue.search('[,]') > -1) { // for  multi-select list
            var expectedValues = expectedValue.split(',').sort().toString();
            var values = currentValue ? currentValue.sort().toString() : '';
            if (conditionSeparaor === ShowCondition.CONDITION_NOT_EQUALS) {
                return expectedValues !== values;
            }
            else {
                return expectedValues === values;
            }
        }
        else if (expectedValue.endsWith('*') && currentValue && conditionSeparaor !== ShowCondition.CONDITION_NOT_EQUALS) {
            return currentValue.startsWith(this.removeStarChar(expectedValue));
        }
        else {
            // changed from '===' to '==' to cover number field conditions
            if (conditionSeparaor === ShowCondition.CONDITION_NOT_EQUALS) {
                var formatCurrentValue = currentValue ? currentValue.toString().trim() : '';
                if ('*' === expectedValue && formatCurrentValue !== '') {
                    return false;
                }
                var formatExpectedValue = expectedValue ? expectedValue.toString().trim() : '';
                return formatCurrentValue != formatExpectedValue; // tslint:disable-line
            }
            else {
                return currentValue == expectedValue || this.okIfBothEmpty(expectedValue, currentValue); // tslint:disable-line
            }
        }
    };
    ShowCondition.prototype.checkValueContains = function (expectedValue, currentValue) {
        if (expectedValue.search(',') > -1) {
            var expectedValues = expectedValue.split(',').sort();
            var values_1 = currentValue ? currentValue.sort().toString() : '';
            return expectedValues.every(function (item) { return values_1.search(item) >= 0; });
        }
        else {
            var values = currentValue && Array.isArray(currentValue) ? currentValue.toString() : '';
            return values.search(expectedValue) >= 0;
        }
    };
    ShowCondition.prototype.findValueForComplexCondition = function (fields, head, tail, path) {
        var headField = fields[head];
        if (tail.length === 0) {
            if (this.isDynamicList(headField)) {
                return headField.value.code;
            }
            else {
                return headField;
            }
        }
        else {
            if (Array.isArray(headField)) {
                // use the path to resolve which array element we refer to
                if (path.startsWith(head)) {
                    var _a = path.replace(/[\[\]\.]/g, '>').split(/[>]+/g), _ = _a[0], pathTail = _a.slice(1);
                    if (pathTail.length > 0) {
                        try { // Extract collection item by its unique identifier
                            var itemIndex = pathTail[0], valueLabel = pathTail[1], dropNumberPath = pathTail.slice(2);
                            var itemId_1 = itemIndex.replace('id:', '');
                            var item = headField.find(function (_a) {
                                var id = _a.id;
                                return id === itemId_1;
                            });
                            if (!item) {
                                return null;
                            }
                            // Item value must be extracted here as `value` is not included in tail for collection items
                            var itemValue = item[valueLabel];
                            return this.findValueForComplexCondition(itemValue, tail[0], tail.slice(1), dropNumberPath.join('>'));
                        }
                        catch (e) {
                            console.log('Error while extracting collection item', pathTail[0], e);
                        }
                    }
                }
                else {
                    console.log('Path in formArray should start with ', head, ', full path: ', path);
                }
            }
            else {
                if (path) {
                    var _b = path.replace(/[\[\]\.]/g, '>').split(/[>]+/g), _ = _b[0], pathTail = _b.slice(1);
                    return this.findValueForComplexCondition(headField, tail[0], tail.slice(1), pathTail.join('>'));
                }
                else {
                    return this.findValueForComplexCondition(headField, tail[0], tail.slice(1), path);
                }
            }
        }
    };
    ShowCondition.prototype.isDynamicList = function (dynamiclist) {
        return dynamiclist
            && typeof dynamiclist === 'object'
            && dynamiclist.hasOwnProperty('value')
            && dynamiclist.hasOwnProperty('list_items');
    };
    ShowCondition.prototype.unquoted = function (str) {
        return str.replace(/^"|"$/g, '');
    };
    ShowCondition.prototype.removeStarChar = function (s) {
        return s.substring(0, s.length - 1);
    };
    ShowCondition.prototype.matchByContextFields = function (contextFields) {
        return this.match(FieldsUtils.toValuesMap(contextFields));
    };
    ShowCondition.prototype.okIfBothEmpty = function (right, value) {
        return value === null && (right === '');
    };
    ShowCondition.AND_CONDITION_REGEXP = new RegExp('\\sAND\\s(?![^"]*"(?:(?:[^"]*"){2})*[^"]*$)', 'g');
    ShowCondition.OR_CONDITION_REGEXP = new RegExp('\\sOR\\s(?![^"]*"(?:(?:[^"]*"){2})*[^"]*$)', 'g');
    ShowCondition.CONDITION_NOT_EQUALS = '!=';
    ShowCondition.CONDITION_EQUALS = '=';
    ShowCondition.CONTAINS = 'CONTAINS';
    return ShowCondition;
}());
export { ShowCondition };
//# sourceMappingURL=conditional-show.model.js.map