"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ColumnFilterInternalApi = void 0;
const tslib_1 = require("tslib");
const LayoutRedux = tslib_1.__importStar(require("../../Redux/ActionsReducers/LayoutRedux"));
const ModuleConstants = tslib_1.__importStar(require("../../Utilities/Constants/ModuleConstants"));
const ArrayExtensions_1 = tslib_1.__importStar(require("../../Utilities/Extensions/ArrayExtensions"));
const StringExtensions_1 = tslib_1.__importDefault(require("../../Utilities/Extensions/StringExtensions"));
const windowFactory_1 = require("../../View/Components/Popups/WindowPopups/windowFactory");
const ApiBase_1 = require("../Implementation/ApiBase");
class ColumnFilterInternalApi extends ApiBase_1.ApiBase {
    /**
     * Returns Predicate Definition for given Column and Quick Filter shortcut
     * @param shortcut Quick Filter shortcut to lookup
     * @param column AdapTable Column being Filtered
     */
    findPredicateDefByShortcut(shortcut, column) {
        return this.getColumnFilterApi()
            .getFilterPredicateDefsForColumn(column)
            .find((predicateDef) => this.getPredicateDefShortcuts(predicateDef)?.includes(shortcut));
    }
    /**
     * Creates an Equality Filter based on given Grid Cells
     * @param gridCells cells to create Filter for
     */
    createValuesColumnFilterForCells(gridCells) {
        if (!gridCells) {
            return null;
        }
        const filter = {
            ColumnId: gridCells[0].column.columnId,
            Predicates: [
                {
                    PredicateId: 'In',
                    Inputs: [...new Set(gridCells.map((gc) => gc.displayValue))],
                },
            ],
        };
        const [savedFilter] = this.getColumnFilterApi().setColumnFilters([filter]) || [null];
        return savedFilter;
    }
    /**
     *  Creates an Equality Filter based on given Grid Cell
     * @param gridCell cell to create Filter for
     */
    createEqualityColumnFilterForCell(gridCell) {
        if (!gridCell) {
            return null;
        }
        const column = gridCell.column;
        const filter = {
            ColumnId: column.columnId,
            Predicates: [
                {
                    PredicateId: this.getPredicateApi().internalApi.getEqualityPredicateForDataType(column.dataType),
                    Inputs: [...new Set([gridCell.rawValue])],
                },
            ],
        };
        const [savedFilter] = this.getColumnFilterApi().setColumnFilters([filter]) || [null];
        return savedFilter;
    }
    /**
     * Calls AdapTableQL to evaluate Filter for given Row
     * @param columnFilter Column Filter to use
     * @param node Row Node to evaluate
     */
    evaluateColumnFilter(columnFilter, node) {
        if (!columnFilter.Predicates.length) {
            return true;
        }
        const someInputsAreEmpty = columnFilter.Predicates.some((predicate) => predicate.Inputs?.some((input) => {
            if (typeof input === 'string') {
                return StringExtensions_1.default.IsNullOrEmpty(input);
            }
            if (typeof input === 'number') {
                return isNaN(input);
            }
            return !input;
        }));
        if (someInputsAreEmpty) {
            return true;
        }
        const column = this.getColumnApi().getColumnWithColumnId(columnFilter.ColumnId);
        if (!column) {
            return true;
        }
        const gridCell = this.getGridApi().getGridCellFromRowNode(node, columnFilter.ColumnId);
        if (!gridCell) {
            return true;
        }
        let value = gridCell.normalisedValue;
        const predicateDefHandlerContext = {
            value: value,
            oldValue: null,
            displayValue: gridCell.displayValue,
            node,
            column,
            predicatesOperator: columnFilter.PredicatesOperator,
            ...this.getAdaptableInternalApi().buildBaseContext(),
        };
        return this.getPredicateApi().handlePredicates(columnFilter.Predicates, predicateDefHandlerContext, true);
    }
    /**
     * Checks if the filter action should trigger Column Filtering
     *
     * @param action Filtering Action
     */
    shouldNewColumnFilterTriggerColumnFiltering(action) {
        // trigger filter change only:
        // - new -> new filter is active
        // - clear -> previous filters was active
        // - clearAll -> a filter was active
        // - edit -> same => input change
        // - edit -> different & new is active
        // - edit -> different & old was active
        // - set -> new filter is active
        // filter -> suspend changes
        const isNewAndActive = action.type === LayoutRedux.LAYOUT_COLUMN_FILTER_ADD &&
            this.getColumnFilterApi().isColumnFilterActive(action.columnFilter);
        const isClearAndPreviousWasActive = action.type === LayoutRedux.LAYOUT_COLUMN_FILTER_CLEAR &&
            this.getColumnFilterApi().isColumnFilterActiveForColumn(action.columnId);
        const isClearAllAtLeastOneActiveFilter = action.type === LayoutRedux.LAYOUT_COLUMN_FILTER_CLEAR_ALL &&
            this.getColumnFilterApi()
                .getColumnFilters()
                .some((columnFilter) => this.getColumnFilterApi().isColumnFilterActive(columnFilter));
        let isEditTrigger = false;
        if (action.type === LayoutRedux.LAYOUT_COLUMN_FILTER_EDIT) {
            const newFilter = action.columnFilter;
            const previous = this.getColumnFilterApi().getColumnFilterForColumn(newFilter.ColumnId);
            // same filter edit, so always trigger
            if (previous &&
                newFilter &&
                // same predicates
                (0, ArrayExtensions_1.areArraysEqual)(previous.Predicates.map((p) => p.PredicateId), newFilter.Predicates.map((p) => p.PredicateId))) {
                isEditTrigger = true;
                // new filter is active
            }
            else if (this.getColumnFilterApi().isColumnFilterActive(newFilter)) {
                isEditTrigger = true;
            }
            else if (this.getColumnFilterApi().isColumnFilterActive(previous)) {
                // previous filter was active
                isEditTrigger = true;
            }
        }
        const isSetAndActive = action.type === LayoutRedux.LAYOUT_COLUMN_FILTER_SET &&
            this.getColumnFilterApi().isColumnFilterActive(action.columnFilter);
        const isSuspendChanged = [
            LayoutRedux.LAYOUT_COLUMN_FILTER_SUSPEND,
            LayoutRedux.LAYOUT_COLUMN_FILTER_SUSPEND_ALL,
            LayoutRedux.LAYOUT_COLUMN_FILTER_UNSUSPEND,
            LayoutRedux.LAYOUT_COLUMN_FILTER_UNSUSPEND_ALL,
        ].includes(action.type);
        return (isNewAndActive ||
            isClearAndPreviousWasActive ||
            isClearAllAtLeastOneActiveFilter ||
            isEditTrigger ||
            isSetAndActive ||
            isSuspendChanged);
    }
    /**
     * Compares to sets of Column Filters to see if they are identical
     * @param filters1
     * @param filters2
     */
    areColumnFiltersDifferent(oldFilters, newFilters) {
        if (ArrayExtensions_1.default.IsNullOrEmpty(oldFilters) && ArrayExtensions_1.default.IsNullOrEmpty(newFilters)) {
            return false;
        }
        return ArrayExtensions_1.default.areArraysNotEqual(oldFilters, newFilters);
    }
    getPredicateDefShortcuts(predicateDef) {
        const shortcuts = this.getFilterOptions().columnFilterOptions.quickFilterWildcards;
        let predicateShortcuts = predicateDef.shortcuts;
        const predicateId = predicateDef.id;
        if (shortcuts?.[predicateId] && Array.isArray(shortcuts[predicateId])) {
            predicateShortcuts = shortcuts[predicateId];
        }
        return predicateShortcuts;
    }
    showQuickFilterDropdown(columnId) {
        const hideQuickFilterDropdownFunction = this.getFilterOptions().columnFilterOptions.hideQuickFilterDropdown;
        if (hideQuickFilterDropdownFunction) {
            const column = this.getColumnApi().getColumnWithColumnId(columnId);
            const columnColumnContext = {
                column: column,
                ...this.getAdaptableInternalApi().buildBaseContext(),
            };
            return !hideQuickFilterDropdownFunction(columnColumnContext);
        }
        return true;
    }
    openColumnFilterPopup(columnId, popupProps) {
        this.getAdaptableInternalApi().showPopupWindow({
            id: windowFactory_1.COLUMN_FILTER_WINDOW,
            title: ModuleConstants.ColumnFilterFriendlyName,
            icon: 'filter',
            factoryId: windowFactory_1.COLUMN_FILTER_WINDOW,
            popupProps: {
                value: columnId,
                size: {
                    width: 380,
                    height: 450,
                },
                ...popupProps,
            },
        });
    }
}
exports.ColumnFilterInternalApi = ColumnFilterInternalApi;
