import { AdaptableModuleBase } from './AdaptableModuleBase';
import * as ModuleConstants from '../Utilities/Constants/ModuleConstants';
import * as LayoutRedux from '../Redux/ActionsReducers/LayoutRedux';
import * as InternalRedux from '../Redux/ActionsReducers/InternalRedux';
import { FilterStatusBarSubPanelPopover } from '../View/Filter/FilterStatusBarSubPanelPopover';
import { getFilterPreview } from './Utilities/Layout/getLayoutFilterViewItems';
export class ColumnFilterModule extends AdaptableModuleBase {
    constructor(api) {
        super(ModuleConstants.ColumnFilterModuleId, ModuleConstants.ColumnFilterFriendlyName, 'filter', 'FilterPopup', 'Advanced filtering capability allows users to see precisely the data they want', api);
    }
    onAdaptableReady() {
        if (this.api.optionsApi.getFilterOptions().columnFilterOptions.showQuickFilter == false) {
            this.api.filterApi.columnFilterApi.hideQuickFilterBar();
        }
        else {
            this.api.filterApi.columnFilterApi.showQuickFilterBar();
        }
        const columnFilters = this.api.filterApi.columnFilterApi.getColumnFilters();
        columnFilters.forEach((cf) => {
            if (!this.api.columnApi.isColumnInGrid(cf.ColumnId)) {
                this.api.logError('Column Filter contains missing column: ' + cf.ColumnId);
            }
        });
        this.api.internalApi
            .getDataService()
            .on('CellDataChanged', (cellDataChangedInfo) => {
            const changedColumnId = cellDataChangedInfo.column.columnId;
            this.api.filterApi.columnFilterApi.resetFilterValues(changedColumnId);
        });
        // we reset the filter cache on sort change, because we might have columns
        // with "In" filters, with custom values, which use `context.orderedValues`
        // customInFilterValues: (context: CustomInFilterValuesContext<Car>) => {
        //   return context.orderedValues;
        // }
        // and that order will most likely change when sorting happens
        // so we need to reset the cached filter values when sorting changes
        this.api.eventApi.on('GridSorted', () => {
            this.api.filterApi.columnFilterApi.resetAllFilterValues();
        });
    }
    setModuleEntitlement() {
        if (!this.api.optionsApi.getFilterOptions().useAdaptableFiltering) {
            this.AccessLevel = 'Hidden';
        }
        else {
            this.AccessLevel = this.api.entitlementApi.getEntitlementAccessLevelForModule(this.moduleInfo.ModuleName);
        }
    }
    getModuleAdaptableObjects() {
        return this.api.filterApi.columnFilterApi.getColumnFilters();
    }
    getExplicitlyReferencedColumnIds(columnFilter) {
        return [columnFilter.ColumnId];
    }
    hasNamedQueryReferences() {
        return false;
    }
    createColumnMenuItems(column) {
        let columnFilterMenuItems = [];
        if (column &&
            column.filterable &&
            this.api.optionsApi.getFilterOptions().useAdaptableFiltering) {
            if (this.api.gridApi.isQuickFilterAvailable()) {
                const isFilterVisible = this.api.filterApi.columnFilterApi.isQuickFilterVisible();
                if (this.isModuleEditable() &&
                    this.api.optionsApi.getFilterOptions().useAdaptableFiltering) {
                    columnFilterMenuItems.push(this.createMenuItemReduxAction(isFilterVisible ? 'column-filter-bar-hide' : 'column-filter-bar-show', isFilterVisible ? 'Hide Filter Bar' : 'Show Filter Bar', isFilterVisible ? 'filter-off' : 'filter', isFilterVisible
                        ? InternalRedux.QuickFilterBarHide()
                        : InternalRedux.QuickFilterBarShow()));
                }
            }
            const existingColumnFilter = this.api.filterApi.columnFilterApi.getColumnFilterForColumn(column.columnId);
            if (existingColumnFilter) {
                columnFilterMenuItems.push(this.createMenuItemReduxAction('column-filter-clear', 'Clear Filter', 'close', LayoutRedux.LayoutColumnFilterClear(existingColumnFilter.ColumnId)));
                columnFilterMenuItems.push(this.createMenuItemReduxAction(existingColumnFilter.IsSuspended ? 'column-filter-unsuspend' : 'column-filter-suspend', existingColumnFilter.IsSuspended ? 'Unsuspend Filter' : 'Suspend Filter', existingColumnFilter.IsSuspended ? 'resume' : 'pause', existingColumnFilter.IsSuspended
                    ? LayoutRedux.LayoutColumnFilterUnSuspend(existingColumnFilter)
                    : LayoutRedux.LayoutColumnFilterSuspend(existingColumnFilter)));
            }
            return columnFilterMenuItems;
        }
    }
    createContextMenuItems(menuContext) {
        if (!menuContext.isRowGroupColumn && this.isModuleVisible()) {
            if (menuContext.adaptableColumn &&
                menuContext.adaptableColumn.filterable &&
                menuContext.isSingleSelectedColumn &&
                menuContext.gridCell != null &&
                this.api.optionsApi.getFilterOptions().useAdaptableFiltering) {
                const existingColumnFilter = this.api.filterApi.columnFilterApi.getColumnFilterForColumn(menuContext.adaptableColumn.columnId);
                if (!existingColumnFilter) {
                    if (!menuContext.isRowGroupColumn && !menuContext.isGroupedNode) {
                        let isMultiple = menuContext.selectedCellInfo.gridCells.length > 1;
                        let clickFunction = isMultiple
                            ? () => {
                                this.api.filterApi.columnFilterApi.internalApi.createValuesColumnFilterForCells(menuContext.selectedCellInfo.gridCells);
                            }
                            : () => {
                                this.api.filterApi.columnFilterApi.internalApi.createEqualityColumnFilterForCell(menuContext.selectedCellInfo.gridCells[0]);
                            };
                        return [
                            this.createMenuItemClickFunction('column-filter-on-cell-value', isMultiple ? 'Filter on Cell Values' : 'Filter on Cell Value', this.moduleInfo.Glyph, clickFunction),
                        ];
                    }
                }
                else {
                    return [
                        this.createMenuItemReduxAction('column-filter-clear', 'Clear Filter', 'close', LayoutRedux.LayoutColumnFilterClear(existingColumnFilter.ColumnId)),
                        this.createMenuItemClickFunction(existingColumnFilter.IsSuspended
                            ? 'column-filter-unsuspend'
                            : 'column-filter-suspend', existingColumnFilter.IsSuspended ? 'Unsuspend Filter' : 'Suspend Filter', existingColumnFilter.IsSuspended ? 'resume' : 'pause', existingColumnFilter.IsSuspended
                            ? () => {
                                this.api.filterApi.columnFilterApi.unSuspendColumnFilter(existingColumnFilter);
                            }
                            : () => {
                                this.api.filterApi.columnFilterApi.suspendColumnFilter(existingColumnFilter);
                            }),
                    ];
                }
            }
        }
    }
    getTeamSharingAction() {
        return {
            ModuleEntities: this.api.filterApi.columnFilterApi.getColumnFilters(),
            AddAction: LayoutRedux.LayoutColumnFilterAdd,
            EditAction: LayoutRedux.LayoutColumnFilterEdit, //TODO need to change this to ColumnFilterSet
        };
    }
    toViewCompact(filter) {
        return {
            item: {
                values: [this.api.filterApi.columnFilterApi.columnFilterToString(filter)],
            },
            abObject: filter,
        };
    }
    toView(filter) {
        return {
            items: [
                {
                    name: 'Column',
                    values: [this.api.columnApi.getFriendlyNameForColumnId(filter.ColumnId)],
                },
                {
                    name: 'Filter',
                    values: [getFilterPreview(filter, this.api)],
                },
            ],
            abObject: filter,
        };
    }
    toViewAll() {
        return this.getModuleAdaptableObjects().map((filter) => this.toView(filter));
    }
    getViewProperties() {
        const api = this.api;
        return {
            getSuspendAction: (columnFilter) => LayoutRedux.LayoutColumnFilterSuspend(columnFilter),
            getUnSuspendAction: (columnFilter) => LayoutRedux.LayoutColumnFilterUnSuspend(columnFilter),
            getCompactSuspendAction: (columnFilter) => LayoutRedux.LayoutColumnFilterSuspend(columnFilter),
            getCompactUnSuspendAction: (columnFilter) => LayoutRedux.LayoutColumnFilterUnSuspend(columnFilter),
            getSuspendAllAction: () => LayoutRedux.LayoutColumnFilterSuspendAll(),
            getUnSuspendAllAction: () => LayoutRedux.LayoutColumnFilterUnSuspendAll(),
            getDeleteAction: (columnFilter) => LayoutRedux.LayoutColumnFilterClear(columnFilter.ColumnId),
            getCompactDeleteAction: (columnFilter) => LayoutRedux.LayoutColumnFilterClear(columnFilter.ColumnId),
            getDeleteAllAction: LayoutRedux.LayoutColumnFilterClearAll,
            emptyView: `
        There are no Column Filters applied. \n
        Create Column Filters by using the Filter Components or by editing a Layout.
      `,
            getStatusBarPanelProps() {
                let text;
                const filters = api.filterApi.columnFilterApi.getColumnFilters();
                if (filters.length === 0) {
                    text = '0 Filters';
                }
                else if (filters.length === 1) {
                    text = '1 Filter';
                }
                else {
                    text = filters.length + ' Filters';
                }
                const popover = filters.length ? FilterStatusBarSubPanelPopover : null;
                return {
                    content: text,
                    popover,
                    popoverMinWidth: 320,
                };
            },
        };
    }
}
