import { filterFns } from '../filterFns';
import { isFunction, makeStateUpdater } from '../utils';
//
export const GlobalFiltering = {
    getInitialState: (state) => {
        return {
            globalFilter: undefined,
            ...state,
        };
    },
    getDefaultOptions: (table) => {
        const options = {
            onGlobalFilterChange: makeStateUpdater('globalFilter', table),
            globalFilterFn: 'auto',
            getColumnCanGlobalFilter: (column) => {
                var _a, _b;
                const value = (_b = (_a = table
                    .getCoreRowModel()
                    .flatRows[0]) === null || _a === void 0 ? void 0 : _a._getAllCellsByColumnId()[column.id]) === null || _b === void 0 ? void 0 : _b.getValue();
                return typeof value === 'string' || typeof value === 'number';
            },
        };
        return options;
    },
    createColumn: (column, table) => {
        column.getCanGlobalFilter = () => {
            var _a, _b, _c, _d, _e, _f;
            return (((_a = column.columnDef.enableGlobalFilter) !== null && _a !== void 0 ? _a : true) &&
                ((_b = table.options.enableGlobalFilter) !== null && _b !== void 0 ? _b : true) &&
                ((_c = table.options.enableFilters) !== null && _c !== void 0 ? _c : true) &&
                ((_f = (_e = (_d = table.options).getColumnCanGlobalFilter) === null || _e === void 0 ? void 0 : _e.call(_d, column)) !== null && _f !== void 0 ? _f : true) &&
                !!column.accessorFn);
        };
    },
    createTable: (table) => {
        table.getGlobalAutoFilterFn = () => {
            return filterFns.includesString;
        };
        table.getGlobalFilterFn = () => {
            var _a, _b;
            const { globalFilterFn } = table.options;
            if (isFunction(globalFilterFn))
                return globalFilterFn;
            if (globalFilterFn === 'auto')
                return table.getGlobalAutoFilterFn();
            return ((_b = (_a = table.options.filterFns) === null || _a === void 0 ? void 0 : _a[globalFilterFn]) !== null && _b !== void 0 ? _b : filterFns[globalFilterFn]);
        };
        table.setGlobalFilter = (updater) => {
            var _a, _b;
            (_b = (_a = table.options).onGlobalFilterChange) === null || _b === void 0 ? void 0 : _b.call(_a, updater);
        };
        table.resetGlobalFilter = (defaultState) => {
            table.setGlobalFilter(defaultState ? undefined : table.initialState.globalFilter);
        };
    },
};
