"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = __importStar(require("react"));
var ramda_1 = require("ramda");
var mdm_sdk_1 = require("@reltio/mdm-sdk");
var EmptyStub_1 = require("../EmptyStub");
var attributesSelector_1 = require("../helpers/attributesSelector");
var helpers_1 = require("./helpers");
var AttributesFilterSelector_1 = require("../AttributesFilterSelector");
var RowActions_1 = require("./components/RowActions");
var QueryBuilderRowsGroup_1 = require("../QueryBuilderRowsGroup");
var MdmModuleContext_1 = require("../contexts/MdmModuleContext");
var AttributeSelector_1 = require("./components/AttributeSelector");
var useFilterAutoFocus_1 = require("../hooks/useFilterAutoFocus");
var AttributesValuesEditor_1 = require("../AttributesValuesEditor");
var AttributesFiltersBuilder_module_css_1 = __importDefault(require("./AttributesFiltersBuilder.module.css"));
var EMPTY_FILTER = { fieldName: null, filter: null, operator: mdm_sdk_1.SearchOperator.and, values: [] };
var EMPTY_OBJECT = {};
var AttributesFiltersBuilder = function (_a) {
    var _b = _a.classes, classes = _b === void 0 ? EMPTY_OBJECT : _b, attributesTypesGroups = _a.attributesTypesGroups, attributesTypesGroupFilter = _a.attributesTypesGroupFilter, filters = _a.filters, onChange = _a.onChange, _c = _a.components, components = _c === void 0 ? EMPTY_OBJECT : _c, onFilterAttributeChange = _a.onFilterAttributeChange;
    var _d = components, CustomValuesEditor = _d.ValuesEditor, CustomFilterSelector = _d.FilterSelector, _e = _d.LogicalOperator, LogicalOperator = _e === void 0 ? EmptyStub_1.EmptyStub : _e;
    var actualFilters = (0, react_1.useRef)(filters);
    var attributesCountRef = (0, react_1.useRef)(null);
    var metadata = (0, MdmModuleContext_1.useMdmMetadata)();
    actualFilters.current = filters;
    var rowClasses = (0, react_1.useMemo)(function () { return ({
        root: AttributesFiltersBuilder_module_css_1.default.root,
        attributeSelectorContainer: classes.attributeSelectorContainer || AttributesFiltersBuilder_module_css_1.default.attrSelector,
        valuesEditorContainer: classes.valuesEditorContainer || '',
        filterSelectorContainer: AttributesFiltersBuilder_module_css_1.default.filterSelector,
        actionsContainer: AttributesFiltersBuilder_module_css_1.default.actionContainer,
        rowActions: AttributesFiltersBuilder_module_css_1.default.rowActions
    }); }, [classes]);
    var currentEntityType = (0, react_1.useMemo)(function () {
        var entityTypesUris = attributesTypesGroups.map(function (_a) {
            var attributeTypes = _a.attributeTypes;
            var regularAttribute = (0, mdm_sdk_1.findRegularAttribute)(attributeTypes);
            return regularAttribute ? (0, mdm_sdk_1.getBaseUri)(regularAttribute.uri) : null;
        });
        var closestEntityTypeAncestorUri = (0, mdm_sdk_1.findClosestCommonAncestor)(metadata, entityTypesUris);
        return (0, mdm_sdk_1.getEntityType)(metadata, closestEntityTypeAncestorUri);
    }, [attributesTypesGroups, metadata]);
    var attributeSelectorItemsGroups = (0, react_1.useMemo)(function () { return (0, attributesSelector_1.getAttributeSelectorItems)(metadata, attributesTypesGroups, attributesTypesGroupFilter); }, [metadata, attributesTypesGroups]);
    var rowsData = (0, react_1.useMemo)(function () { return (filters.length ? (0, helpers_1.getRowsDataFromFilters)(filters, attributeSelectorItemsGroups) : []); }, [attributeSelectorItemsGroups, filters]);
    var _f = (0, useFilterAutoFocus_1.useFilterAutoFocus)(rowsData), attributeFilterRef = _f.attributeFilterRef, lastAttributesCountRef = _f.lastAttributesCountRef;
    attributesCountRef.current = rowsData.length;
    var handleAttributeSelectorOnOpen = (0, react_1.useCallback)(function () {
        lastAttributesCountRef.current = rowsData.length;
    }, [rowsData.length]);
    var lastRowAttributeSelectorProps = (0, react_1.useMemo)(function () { return ({
        onOpen: handleAttributeSelectorOnOpen
    }); }, [handleAttributeSelectorOnOpen]);
    var addRowAfterIndex = (0, react_1.useCallback)(function (index) {
        var newFilters = __spreadArray([], actualFilters.current, true);
        newFilters.splice(index + 1, 0, EMPTY_FILTER);
        onChange(newFilters);
    }, [onChange]);
    var removeRow = (0, react_1.useCallback)(function (index) {
        var newFilters = __spreadArray([], actualFilters.current, true);
        newFilters.splice(index, 1);
        onChange(newFilters);
    }, [onChange]);
    var duplicateRow = (0, react_1.useCallback)(function (index) {
        var newFilters = __spreadArray([], actualFilters.current, true);
        newFilters.splice(index + 1, 0, __assign({}, actualFilters.current[index]));
        onChange(newFilters);
    }, [onChange]);
    var changeFilter = (0, react_1.useCallback)(function (newFilter, id) {
        var _a;
        var newFilters = (0, ramda_1.evolve)((_a = {},
            _a[id] = (0, ramda_1.always)(newFilter),
            _a), actualFilters.current);
        onChange(newFilters);
    }, [onChange]);
    var addNewFilter = (0, react_1.useCallback)(function (newFilter) {
        onChange(__spreadArray(__spreadArray([], actualFilters.current, true), [newFilter], false));
    }, [onChange]);
    return (react_1.default.createElement(QueryBuilderRowsGroup_1.QueryBuilderRowsGroup, { rowClasses: rowClasses, rowsData: rowsData, AttributeSelectorComponent: AttributeSelector_1.AttributeSelector, FilterSelectorComponent: CustomFilterSelector || AttributesFilterSelector_1.AttributesFilterSelector, ValuesEditorComponent: CustomValuesEditor || AttributesValuesEditor_1.AttributesValuesEditor, ActionsComponent: RowActions_1.RowActions, LogicOperatorComponent: LogicalOperator, filterSelectorRefIndex: lastAttributesCountRef.current, filterSelectorRef: attributeFilterRef, lastRowAttributeSelectorProps: lastRowAttributeSelectorProps, attributeSelectorItemsGroups: attributeSelectorItemsGroups, entityType: currentEntityType, changeFilter: changeFilter, addNewFilter: addNewFilter, addRowAfterIndex: addRowAfterIndex, removeRow: removeRow, duplicateRow: duplicateRow, onFilterAttributeChange: onFilterAttributeChange }));
};
exports.default = (0, react_1.memo)(AttributesFiltersBuilder);
