import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
import _find from '../../node_modules/lodash-es/find.js';
import get from '../../node_modules/lodash-es/get.js';
import isEmpty from '../../node_modules/lodash-es/isEmpty.js';
import isNil from '../../node_modules/lodash-es/isNil.js';
import 'core-js/modules/es.array.concat.js';
import 'core-js/modules/es.symbol.js';
import 'core-js/modules/es.array.filter.js';
import 'core-js/modules/es.array.find.js';
import 'core-js/modules/es.array.find-index.js';
import 'core-js/modules/es.array.includes.js';
import 'core-js/modules/es.array.iterator.js';
import 'core-js/modules/es.array.map.js';
import 'core-js/modules/es.array.sort.js';
import 'core-js/modules/es.number.constructor.js';
import 'core-js/modules/es.object.entries.js';
import 'core-js/modules/es.object.get-own-property-descriptor.js';
import 'core-js/modules/es.object.get-own-property-descriptors.js';
import 'core-js/modules/es.object.keys.js';
import 'core-js/modules/es.object.to-string.js';
import 'core-js/modules/es.object.values.js';
import 'core-js/modules/es.regexp.exec.js';
import 'core-js/modules/es.regexp.to-string.js';
import 'core-js/modules/es.string.includes.js';
import 'core-js/modules/es.string.search.js';
import 'core-js/modules/web.dom-collections.for-each.js';
import 'core-js/modules/web.dom-collections.iterator.js';
import update from 'immutability-helper';
import { firstBy } from 'thenby';
import { isEmptyString, getSortedData, sortTableData, caseInsensitiveSearch } from '../../utils/componentUtilityFunctions.js';
import { fillArrWithRowIds } from '../../utils/tableReducer.js';
import { FILTER_EMPTY_STRING } from '../../constants/Filters.js';
import { TABLE_COLUMN_RESIZE, TABLE_ROW_EXPAND, TABLE_COLUMN_ORDER, TABLE_TOOLBAR_TOGGLE, TABLE_ROW_ACTION_ERROR, TABLE_ROW_ACTION_COMPLETE, TABLE_ROW_ACTION_EDIT, TABLE_ROW_ACTION_START, TABLE_PAGE_CHANGE, TABLE_ROW_LOAD_MORE, TABLE_MULTI_SORT_REMOVE_COLUMN, TABLE_MULTI_SORT_ADD_COLUMN, TABLE_MULTI_SORT_CLEAR, TABLE_MULTI_SORT_CANCEL, TABLE_MULTI_SORT_SAVE, TABLE_MULTI_SORT_TOGGLE_MODAL, TABLE_TOGGLE_AGGREGATIONS, TABLE_ADVANCED_FILTER_APPLY, TABLE_ADVANCED_FILTER_CANCEL, TABLE_ADVANCED_FILTER_CREATE, TABLE_ADVANCED_FILTER_CHANGE, TABLE_ADVANCED_FILTER_REMOVE, TABLE_ADVANCED_FILTER_TOGGLE, TABLE_REGISTER, TABLE_ROW_SELECT_ALL, TABLE_ROW_SELECT, TABLE_COLUMN_SORT, TABLE_ACTION_APPLY, TABLE_ACTION_CANCEL, TABLE_SEARCH_APPLY, TABLE_FILTER_CLEAR, TABLE_FILTER_APPLY } from './tableActionCreators.js';
import { baseTableReducer } from './baseTableReducer.js';
import { findRow } from './tableUtilities.js';

function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var searchWithEmptyString = function searchWithEmptyString(keys, searchTerm, baseSearch) {
  if (searchTerm === FILTER_EMPTY_STRING) {
    return keys.some(function (key) {
      return isEmptyString(key);
    });
  }
  return baseSearch(keys, searchTerm);
};
var arraySearchWithEmptyString = function arraySearchWithEmptyString(arr, item) {
  if (arr.includes(FILTER_EMPTY_STRING) && isEmptyString(item)) {
    return true;
  }
  return arr.includes(item);
};

/**
 * Default function to compare value 1 and 2
 * @param {*} value1, filter value
 * @param {*} value2, actual
 * returns true if value1 contains value2 for strings, and true if value1 === value2 for numbers
 */
var defaultComparison = function defaultComparison(value1, value2) {
  return !isNil(value1) && typeof value1 === 'number' // only if the column value filter is not null/undefined
  ? value1 === Number(value2) // for a number type, attempt to convert filter to number and direct compare
  : !isNil(value1) &&
  // type string do a lowercase includes comparison
  searchWithEmptyString([value1 === null || value1 === void 0 ? void 0 : value1.toString()], value2 === null || value2 === void 0 ? void 0 : value2.toString(), caseInsensitiveSearch);
};
var runSimpleFilters = function runSimpleFilters(data, filters, columns) {
  return data.filter(function (_ref) {
    var values = _ref.values;
    return (
      // return false if a value doesn't match a valid filter
      filters.reduce(function (acc, _ref2) {
        var columnId = _ref2.columnId,
          value = _ref2.value;
        if (typeof value === 'number' || typeof value === 'string' || typeof value === 'boolean' || Array.isArray(value) || value instanceof Date) {
          if (!isNil(columns)) {
            var _ref3 = _find(columns, {
                id: columnId
              }) || {},
              filter = _ref3.filter;
            var filterFunction = filter === null || filter === void 0 ? void 0 : filter.filterFunction;
            if (Array.isArray(value) && !isEmpty(value)) {
              return acc && (filterFunction ? filterFunction(values[columnId], value) : arraySearchWithEmptyString(value, values[columnId]));
            }
            return acc && (filterFunction ? filterFunction(values[columnId], value) : defaultComparison(values[columnId], value));
          }
          if (Array.isArray(value) && !isEmpty(value)) {
            return acc && arraySearchWithEmptyString(value, values[columnId]);
          }
          return acc && defaultComparison(values[columnId], value);
        }
        return false;
      }, true)
    );
  });
};
var operands = {
  NEQ: function NEQ(a, b) {
    return a !== b;
  },
  LT: function LT(a, b) {
    return a < b;
  },
  LTOET: function LTOET(a, b) {
    return a <= b;
  },
  EQ: function EQ(a, b) {
    return a === b;
  },
  GTOET: function GTOET(a, b) {
    return a >= b;
  },
  GT: function GT(a, b) {
    return a > b;
  },
  CONTAINS: function CONTAINS(a, b) {
    return a.includes(b);
  }
};

/**
 * Recursively check each rule and determine if it's a normal rule or a ruleGroup.
 * If it's a group dig deeper into the tree passing the values and logic down as we go.
 * If it's a normal rule just run `every` on all the rules for 'ALL' logic and `some`
 * for 'ANY' logic.
 *
 * @param {string} logic 'ALL' or 'ANY'
 * @param {Array<Object>} rules Array of all the rules in this group
 * @param {object} values The values for each column in this row of the data
 *
 * @returns boolean
 */
var reduceRuleGroup = function reduceRuleGroup(logic, rules, values) {
  var processRules = function processRules(_ref4) {
    var _values$columnId;
    var columnId = _ref4.columnId,
      operand = _ref4.operand,
      childLogic = _ref4.groupLogic,
      childRules = _ref4.rules,
      filterValue = _ref4.value;
    if (childLogic && Array.isArray(childRules)) {
      return reduceRuleGroup(childLogic, childRules, values);
    }
    var columnValue = (_values$columnId = values[columnId]) === null || _values$columnId === void 0 ? void 0 : _values$columnId.toString();
    var comparitor = operands[operand];
    return comparitor(columnValue, filterValue);
  };
  if (logic === 'ALL') {
    return rules.every(processRules);
  }
  if (logic === 'ANY') {
    return rules.some(processRules);
  }
  return false;
};

/**
 * Loop through all the currently active advanced filters TREATING THEM AS 'AND' CONDITIONS
 * to determine which rows should be shown.
 *
 * @param {Array<Object>} data tableData
 * @param {Array<{filterId: string; filterTitleText: string; filterRules: Object}>} advancedFilters All the currently active filters
 * @returns boolean
 */
var runAdvancedFilters = function runAdvancedFilters(data, advancedFilters) {
  return data.filter(function (_ref5) {
    var values = _ref5.values;
    return advancedFilters.every(function (_ref6) {
      var _ref6$filterRules = _ref6.filterRules,
        groupLogic = _ref6$filterRules.groupLogic,
        rules = _ref6$filterRules.rules;
      return reduceRuleGroup(groupLogic, rules, values);
    });
  });
};

/**
 * Little utility to filter data
 * @param {Array<Object>} data data to filter
 * @param {Array<{columnId: string, value: any}>} filters
 * @param {Array<Object>} columns AKA headers
 */
var filterData = function filterData(data, filters, columns, advancedFilters) {
  var hasSimpleFilters = Array.isArray(filters) && filters.length;
  var hasAdvancedFilters = Array.isArray(advancedFilters) && advancedFilters.length;
  if (!hasSimpleFilters && !hasAdvancedFilters) {
    return data;
  }
  if (!hasAdvancedFilters) {
    return runSimpleFilters(data, filters, columns);
  }
  if (!hasSimpleFilters) {
    return runAdvancedFilters(data, advancedFilters);
  }
  return runSimpleFilters(runAdvancedFilters(data, advancedFilters), filters, columns);
};

// Little utility to search
var searchData = function searchData(data, searchString) {
  return searchString && searchString !== '' ? data.filter(function (_ref7 // globally check row values for a match
  ) {
    var values = _ref7.values;
    var foundIndex = Object.values(values).findIndex(function (value) {
      if (typeof value === 'number' || typeof value === 'string' || typeof value === 'boolean') {
        if (!isNil(value)) {
          return searchWithEmptyString([value.toString()], searchString.toString(), caseInsensitiveSearch);
        }
      }
      return false;
    });
    return foundIndex !== -1;
  }) : data;
};
var getCustomColumnSort = function getCustomColumnSort(columns, columnId) {
  var currentlySortedColumn = columnId && columns && columns.find(function (column) {
    return column.id === columnId;
  });
  return currentlySortedColumn && currentlySortedColumn.sortFunction; // see if there's a custom sort function passed
};

/**
 * multi-sort helper for more readable code.
 *
 * @param {array} sort An array of sort objects [{columnId: string, direction: 'ASC' | 'DESC'}]
 * @param {array} columns An array of table columns matching the table column prop
 * @param {array} data An array of row data for the Table
 *
 * @returns the table data sorted by multiple dimensions
 */
var handleMultiSort = function handleMultiSort(sort, columns, data) {
  // setup the stack with a inert firstBy, so that we can jump straight into the
  // thenBys below from the sort array
  var sortStack = firstBy(function () {
    return 0;
  });
  sort.forEach(function (_ref8) {
    var columnId = _ref8.columnId,
      direction = _ref8.direction;
    var customSortFn = getCustomColumnSort(columns, columnId);
    if (customSortFn) {
      var sortedValues = customSortFn({
        data: data,
        columnId: columnId,
        direction: direction
      }).map(function (_ref9) {
        var values = _ref9.values;
        return values;
      });
      sortStack = sortStack.thenBy(function (row) {
        return row.values[columnId];
      }, {
        cmp: function cmp(a, b) {
          return sortedValues.findIndex(function (row) {
            return row[columnId] === a;
          }) - sortedValues.findIndex(function (row) {
            return row[columnId] === b;
          });
        }
      });
    } else {
      sortStack = sortStack.thenBy(function (row) {
        return row.values[columnId];
      }, {
        cmp: sortTableData(),
        direction: direction === 'ASC' ? 'asc' : 'desc'
      });
    }
  });
  return data.sort(sortStack);
};

// little utility to both sort and filter
var filterSearchAndSort = function filterSearchAndSort(data) {
  var sort = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var search = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  var filters = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
  var columns = arguments.length > 4 ? arguments[4] : undefined;
  var advancedFilters = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : [];
  var value = search.value,
    defaultValue = search.defaultValue;
  var searchValue = value !== null && value !== void 0 ? value : defaultValue;
  var filteredData = filterData(data, filters, columns, advancedFilters);
  var searchedData = searchValue && searchValue !== '' ? searchData(filteredData, searchValue) : filteredData;
  if (isEmpty(sort)) {
    return searchedData;
  }
  if (Array.isArray(sort)) {
    return handleMultiSort(sort, columns, searchedData);
  }
  var columnId = sort.columnId,
    direction = sort.direction;
  return getCustomColumnSort(columns, columnId) ? getCustomColumnSort(columns, columnId)({
    data: searchedData,
    columnId: columnId,
    direction: direction
  }) : getSortedData(searchedData, columnId, direction);
};

/** This reducer handles sort, filter and search that needs data otherwise it proxies for the baseTableReducer */
var tableReducer = function tableReducer() {
  var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var action = arguments.length > 1 ? arguments[1] : undefined;
  switch (action.type) {
    // Filter Actions
    case TABLE_FILTER_APPLY:
      {
        var newFilters = Object.entries(action.payload).map(function (_ref10) {
          var _ref11 = _slicedToArray(_ref10, 2),
            key = _ref11[0],
            value = _ref11[1];
          return value !== '' ? {
            columnId: key,
            value: value
          } : null;
        }).filter(function (i) {
          return i;
        });
        return baseTableReducer(update(state, {
          view: {
            table: {
              filteredData: {
                $set: filterSearchAndSort(state.data, get(state, 'view.table.sort'), get(state, 'view.toolbar.search'), newFilters, get(state, 'columns'))
              }
            }
          }
        }), action);
      }
    case TABLE_FILTER_CLEAR:
      return baseTableReducer(update(state, {
        view: {
          selectedAdvancedFilterIds: {
            $set: []
          },
          table: {
            filteredData: {
              $set: filterSearchAndSort(state.data, get(state, 'view.table.sort'), get(state, 'view.toolbar.search'), [], get(state, 'columns'), [])
            }
          }
        }
      }), action);
    case TABLE_SEARCH_APPLY:
      {
        // console.log(state.data.length)
        // Quick search should search within the filtered and sorted data
        var data = filterSearchAndSort(state.data, get(state, 'view.table.sort'), {
          value: action.payload
        }, get(state, 'view.filters'), get(state, 'columns'));
        return baseTableReducer(update(state, {
          view: {
            table: {
              filteredData: {
                $set: data
              }
            }
          }
        }), action);
      }

    // Batch Actions
    case TABLE_ACTION_CANCEL:
      return baseTableReducer(state, action);
    case TABLE_ACTION_APPLY:
      {
        var filteredData = state.view.table.filteredData;
        var _data = filteredData || state.data;
        // only update the data and filtered data if deleted
        if (action.payload === 'delete') {
          var selectedIds = state.view.table.selectedIds;
          var pagination = state.view.pagination;
          var totalItems = pagination.totalItems - selectedIds.length;
          var numberOfPages = Math.ceil(totalItems / pagination.pageSize);
          var page = pagination.page > numberOfPages ? numberOfPages : pagination.page;
          return baseTableReducer(update(state, {
            data: {
              $set: state.data.filter(function (i) {
                return !selectedIds.includes(i.id);
              })
            },
            view: {
              table: {
                filteredData: {
                  $set: _data.filter(function (i) {
                    return !selectedIds.includes(i.id);
                  })
                }
              },
              pagination: {
                $set: _objectSpread(_objectSpread({}, pagination), {}, {
                  totalItems: totalItems,
                  page: page
                })
              }
            }
          }), action);
        }
        return baseTableReducer(state, action);
      }
    // Column operations
    case TABLE_COLUMN_SORT:
      {
        // TODO should check that columnId actually is valid
        var columnId = action.payload;
        var sorts = ['NONE', 'ASC', 'DESC'];
        var currentSort = get(state, 'view.table.sort');
        var isInMultiSort = Array.isArray(currentSort) && currentSort.some(function (column) {
          return column.columnId === columnId;
        });
        var currentSortDir = isInMultiSort ? currentSort.find(function (sort) {
          return sort.columnId === columnId;
        }).direction : currentSort && currentSort.columnId === columnId ? currentSort.direction : 'NONE';
        var nextSortDir = isInMultiSort ? currentSortDir === 'ASC' ? 'DESC' : 'ASC' : sorts[(sorts.findIndex(function (i) {
          return i === currentSortDir;
        }) + 1) % sorts.length];

        // validate if there is any column of timestamp type
        var isTimestampColumn = action.columns && action.columns.filter(function (column) {
          return column.id === columnId && column.type === 'TIMESTAMP';
        }).length > 0;
        var customColumnSort = getCustomColumnSort(get(state, 'columns'), columnId);
        var _filteredData;
        var nextSort;
        if (isInMultiSort) {
          nextSort = currentSort.reduce(function (carry, column) {
            if (column.columnId === columnId) {
              return [].concat(_toConsumableArray(carry), [_objectSpread(_objectSpread({}, column), {}, {
                direction: nextSortDir
              })]);
            }
            return [].concat(_toConsumableArray(carry), [column]);
          }, []);
          _filteredData = handleMultiSort(nextSort, state.columns, state.view.table.filteredData || state.data);
        } else {
          var _state$view$toolbar$s;
          _filteredData = nextSortDir !== 'NONE' ? customColumnSort // if there's a custom column sort apply it
          ? customColumnSort({
            data: state.view.table.filteredData || state.data,
            columnId: columnId,
            direction: nextSortDir
          }) : getSortedData(state.view.table.filteredData || state.data, columnId, nextSortDir, isTimestampColumn) : filterSearchAndSort(state.data, null, {
            value: (_state$view$toolbar$s = state.view.toolbar.search) === null || _state$view$toolbar$s === void 0 ? void 0 : _state$view$toolbar$s.defaultValue
          }, get(state, 'view.filters'), get(state, 'columns'));
        }
        return baseTableReducer(update(state, {
          view: {
            table: {
              filteredData: {
                $set: _filteredData
              }
            }
          }
        }), action);
      }
    case TABLE_ROW_SELECT:
      {
        return baseTableReducer(state, action);
      }
    case TABLE_ROW_SELECT_ALL:
      {
        return baseTableReducer(state, action);
      }
    // By default we need to setup our sorted and filteredData and turn off the loading state
    case TABLE_REGISTER:
      {
        var _state$view$table$loa, _state$view, _view$toolbar, _state$view2, _view$table$rowAction, _view$table;
        var updatedData = action.payload.data || state.data;

        // The only thing that changes after additional child rows have been loaded is the
        // actual data, so we use that diff to find out which ids in loadingMoreIds that
        // we should keep.
        var loadingMoreIds = (_state$view$table$loa = (_state$view = state.view) === null || _state$view === void 0 || (_state$view = _state$view.table) === null || _state$view === void 0 || (_state$view = _state$view.loadingMoreIds) === null || _state$view === void 0 ? void 0 : _state$view.filter(function (loadMoreRowId) {
          var _findRow, _findRow2;
          var oldChildCount = (_findRow = findRow(loadMoreRowId, state.data)) === null || _findRow === void 0 || (_findRow = _findRow.children) === null || _findRow === void 0 ? void 0 : _findRow.length;
          var newChildCount = (_findRow2 = findRow(loadMoreRowId, action.payload.data)) === null || _findRow2 === void 0 || (_findRow2 = _findRow2.children) === null || _findRow2 === void 0 ? void 0 : _findRow2.length;
          return oldChildCount === newChildCount;
        })) !== null && _state$view$table$loa !== void 0 ? _state$view$table$loa : [];
        var _action$payload = action.payload,
          view = _action$payload.view,
          _totalItems = _action$payload.totalItems,
          hasUserViewManagement = _action$payload.hasUserViewManagement,
          hasRowSelection = _action$payload.hasRowSelection;
        var _ref12 = get(view, 'pagination') || {},
          pageSize = _ref12.pageSize,
          pageSizes = _ref12.pageSizes,
          _page = _ref12.page;
        var paginationFromState = get(state, 'view.pagination');
        var activeBar = view === null || view === void 0 || (_view$toolbar = view.toolbar) === null || _view$toolbar === void 0 ? void 0 : _view$toolbar.activeBar;
        var activeBarFromState = (_state$view2 = state.view) === null || _state$view2 === void 0 || (_state$view2 = _state$view2.toolbar) === null || _state$view2 === void 0 ? void 0 : _state$view2.activeBar;
        var rowEditMode = activeBarFromState === 'rowEdit';
        var isMultiSelect = hasRowSelection === 'multi';
        var initialDefaultSearch = get(view, 'toolbar.search.defaultValue') || get(view, 'toolbar.search.value');
        // update the column ordering if I'm passed new columns
        // but only if hasUserViewManagement is not active.
        var ordering = hasUserViewManagement ? get(state, 'view.table.ordering') : get(view, 'table.ordering') || get(state, 'view.table.ordering');

        // update the search if a new one is passed
        var searchFromState = get(view, 'toolbar.search');

        // if hasUserViewManagement is active we rely on defaultValue
        var searchTermFromState = hasUserViewManagement ? searchFromState === null || searchFromState === void 0 ? void 0 : searchFromState.defaultValue : searchFromState === null || searchFromState === void 0 ? void 0 : searchFromState.value;
        var nextPageSize = paginationFromState.pageSize || pageSize;
        var nextTotalItems = _totalItems || updatedData.length;
        var nextPage = rowEditMode ? paginationFromState.page : _page || 1;
        var _pagination = get(state, 'view.pagination') ? {
          totalItems: {
            $set: nextTotalItems
          },
          pageSize: {
            $set: nextPageSize
          },
          pageSizes: {
            $set: pageSizes
          },
          page: {
            $set: nextPage
          }
        } : {};
        var advancedFilters = get(view, 'advancedFilters', []);
        var selectedAdvancedFilterIds = get(view, 'selectedAdvancedFilterIds') || get(state, 'view.selectedAdvancedFilterIds', []);
        var selectedAdvancedFilters = advancedFilters.filter(function (advFilter) {
          return selectedAdvancedFilterIds.includes(advFilter.filterId);
        });
        var rowActionsFromState = get(state, 'view.table.rowActions', []);
        var rowActionsFromProps = (_view$table$rowAction = view === null || view === void 0 || (_view$table = view.table) === null || _view$table === void 0 ? void 0 : _view$table.rowActions) !== null && _view$table$rowAction !== void 0 ? _view$table$rowAction : [];
        var rowActions = rowActionsFromState
        // filter actions from state that have been removed from props
        .filter(function (_ref13) {
          var rowId = _ref13.rowId;
          return rowActionsFromProps.some(function (row) {
            return row.rowId === rowId;
          });
        }).concat(
        // add actions from props that aren't in state
        rowActionsFromProps.filter(function (_ref14) {
          var rowId = _ref14.rowId;
          return rowActionsFromState.every(function (row) {
            return row.rowId !== rowId;
          });
        }));
        var columns = get(state, 'columns');
        var filtersInit = get(state, 'view.filters');

        // allow filtering by empty string during the table initialization
        var filters = filtersInit.map(function (filter) {
          if (isEmptyString(filter.value)) {
            var emptyFilterId = filter.columnId;
            var columnWithEmptyFilter = columns.find(function (el) {
              return el.id === emptyFilterId;
            });
            if (!isEmpty(columnWithEmptyFilter.filter.options)) {
              return _objectSpread(_objectSpread({}, filter), {}, {
                value: FILTER_EMPTY_STRING
              });
            }
          }
          return filter;
        });
        var allRowsId = [];
        updatedData.forEach(function (row) {
          return fillArrWithRowIds(row, allRowsId);
        });
        var _selectedIds = view ? view.table.selectedIds : [];
        var isSelectingAll = isMultiSelect && (_selectedIds === null || _selectedIds === void 0 ? void 0 : _selectedIds.length) === allRowsId.length;
        var isSelectAllSelected = isSelectingAll ? true : view ? view.table.isSelectAllSelected : false;
        return update(state, {
          data: {
            $set: updatedData
          },
          view: {
            pagination: _pagination,
            advancedFilters: {
              $set: advancedFilters
            },
            toolbar: {
              initialDefaultSearch: {
                $set: initialDefaultSearch
              },
              search: {
                $set: searchFromState
              },
              activeBar: {
                $set: activeBar
              },
              rowEditBarButtons: {
                $set: get(view, 'toolbar.rowEditBarButtons')
              },
              hideClearAllFiltersButton: {
                $set: get(view, 'toolbar.hideClearAllFiltersButton')
              }
            },
            table: {
              ordering: {
                $set: ordering
              },
              filteredData: {
                $set: filterSearchAndSort(updatedData, get(state, 'view.table.sort'), {
                  value: searchTermFromState
                }, filters, columns, selectedAdvancedFilters)
              },
              loadingState: {
                $set: {
                  isLoading: action.payload.isLoading,
                  rowCount: get(state, 'view.table.loadingState.rowCount') || 0,
                  columnCount: get(state, 'view.table.loadingState.columnCount') || 0
                }
              },
              rowActions: {
                $set: rowActions
              },
              // Reset the selection to the previous values
              selectedIds: {
                $set: _selectedIds
              },
              isSelectAllIndeterminate: {
                $set: view ? view.table.isSelectAllIndeterminate : false
              },
              isSelectAllSelected: {
                $set: isSelectAllSelected
              },
              loadingMoreIds: {
                $set: loadingMoreIds
              },
              singleRowEditButtons: {
                $set: get(view, 'table.singleRowEditButtons')
              }
            }
          }
        });
      }
    case TABLE_ADVANCED_FILTER_TOGGLE:
      {
        var isOpen = state.view.toolbar.advancedFilterFlyoutOpen === true;
        return update(state, {
          view: {
            toolbar: {
              $set: {
                advancedFilterFlyoutOpen: !isOpen
              }
            }
          }
        });
      }
    case TABLE_ADVANCED_FILTER_REMOVE:
      {
        var filterId = action.payload.filterId;
        var newSelectedFilters = state.view.selectedAdvancedFilterIds.filter(function (id) {
          return id !== filterId;
        });
        return update(state, {
          view: {
            selectedAdvancedFilterIds: {
              $set: newSelectedFilters
            }
          }
        });
      }
    case TABLE_ADVANCED_FILTER_CHANGE:
      {
        return state;
      }
    case TABLE_ADVANCED_FILTER_CREATE:
      {
        return state;
      }
    case TABLE_ADVANCED_FILTER_CANCEL:
      {
        return update(state, {
          view: {
            toolbar: {
              $set: {
                advancedFilterFlyoutOpen: false
              }
            }
          }
        });
      }
    case TABLE_ADVANCED_FILTER_APPLY:
      {
        var _action$payload$simpl, _action$payload2;
        var newSimpleFilters = Object.entries((_action$payload$simpl = (_action$payload2 = action.payload) === null || _action$payload2 === void 0 ? void 0 : _action$payload2.simple) !== null && _action$payload$simpl !== void 0 ? _action$payload$simpl : {}).map(function (_ref15) {
          var _ref16 = _slicedToArray(_ref15, 2),
            key = _ref16[0],
            value = _ref16[1];
          return value !== '' ? {
            columnId: key,
            value: value
          } : null;
        }).filter(function (i) {
          return i;
        });
        var newAdvancedFilters = state.view.advancedFilters.filter(function (advFilter) {
          var _action$payload3;
          return action === null || action === void 0 || (_action$payload3 = action.payload) === null || _action$payload3 === void 0 || (_action$payload3 = _action$payload3.advanced) === null || _action$payload3 === void 0 || (_action$payload3 = _action$payload3.filterIds) === null || _action$payload3 === void 0 ? void 0 : _action$payload3.includes(advFilter.filterId);
        });
        return baseTableReducer(update(state, {
          view: {
            selectedAdvancedFilterIds: {
              $set: newAdvancedFilters.map(function (advFilter) {
                return advFilter.filterId;
              })
            },
            table: {
              filteredData: {
                $set: filterSearchAndSort(state.data, get(state, 'view.table.sort'), get(state, 'view.toolbar.search'), newSimpleFilters, get(state, 'columns'), newAdvancedFilters)
              }
            },
            toolbar: {
              advancedFilterFlyoutOpen: {
                $set: false
              }
            }
          }
        }), action);
      }
    case TABLE_TOGGLE_AGGREGATIONS:
      {
        return update(state, {
          view: {
            aggregations: {
              isHidden: {
                $set: !state.view.aggregations.isHidden
              }
            }
          }
        });
      }
    case TABLE_MULTI_SORT_TOGGLE_MODAL:
      {
        var _columnId = action.payload.columnId;
        var _currentSort = state.view.table.sort;
        var arrayifiedSort = Array.isArray(_currentSort) ? _currentSort : _currentSort !== undefined ? [_currentSort] : [];
        var alreadySortedBy = arrayifiedSort.some(function (by) {
          return by.columnId === _columnId;
        });
        return update(state, {
          view: {
            table: {
              showMultiSortModal: {
                $set: !state.view.table.showMultiSortModal
              },
              multiSortModal: {
                $set: {
                  anticipatedColumn: !alreadySortedBy ? {
                    columnId: _columnId,
                    direction: 'ASC'
                  } : undefined
                }
              }
            }
          }
        });
      }
    case TABLE_MULTI_SORT_SAVE:
      {
        var _selectedAdvancedFilterIds = get(state, 'view.selectedAdvancedFilterIds', []);
        var _advancedFilters = get(state, 'view.advancedFilters', []);
        var _selectedAdvancedFilters = _advancedFilters.filter(function (advFilter) {
          return _selectedAdvancedFilterIds.includes(advFilter.filterId);
        });
        return update(state, {
          view: {
            table: {
              sort: {
                $set: action.payload
              },
              filteredData: {
                $set: filterSearchAndSort(state.data, action.payload, get(state, 'view.toolbar.search'), get(state, 'view.filters'), get(state, 'columns'), _selectedAdvancedFilters)
              },
              showMultiSortModal: {
                $set: false
              }
            }
          }
        });
      }
    case TABLE_MULTI_SORT_CANCEL:
      {
        return update(state, {
          view: {
            table: {
              showMultiSortModal: {
                $set: false
              }
            }
          }
        });
      }
    case TABLE_MULTI_SORT_CLEAR:
      {
        return update(state, {
          view: {
            table: {
              showMultiSortModal: {
                $set: false
              },
              sort: {
                $set: undefined
              },
              filteredData: {
                $set: filterData(state.data, state.view.filters, state.columns)
              }
            }
          }
        });
      }
    case TABLE_MULTI_SORT_ADD_COLUMN:
      {
        return state;
      }
    case TABLE_MULTI_SORT_REMOVE_COLUMN:
      {
        return state;
      }
    case TABLE_ROW_LOAD_MORE:
      {
        return update(state, {
          view: {
            table: {
              loadingMoreIds: {
                $set: [].concat(_toConsumableArray(state.view.table.loadingMoreIds), [action.payload])
              }
            }
          }
        });
      }

    // Actions that are handled by the base reducer
    case TABLE_PAGE_CHANGE:
    case TABLE_ROW_ACTION_START:
    case TABLE_ROW_ACTION_EDIT:
    case TABLE_ROW_ACTION_COMPLETE:
    case TABLE_ROW_ACTION_ERROR:
    case TABLE_TOOLBAR_TOGGLE:
    case TABLE_COLUMN_ORDER:
    case TABLE_ROW_EXPAND:
    case TABLE_COLUMN_RESIZE:
      return baseTableReducer(state, action);
    default:
      return state;
  }
};

export { defaultComparison, filterData, filterSearchAndSort, getCustomColumnSort, runAdvancedFilters, runSimpleFilters, searchData, tableReducer };
