import _extends from '@babel/runtime/helpers/extends';
import _asyncToGenerator from '@babel/runtime/helpers/asyncToGenerator';
import _typeof from '@babel/runtime/helpers/typeof';
import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import _objectWithoutProperties from '@babel/runtime/helpers/objectWithoutProperties';
import get from '../../node_modules/lodash-es/get.js';
import _merge from '../../node_modules/lodash-es/merge.js';
import _regeneratorRuntime from '@babel/runtime/regenerator';
import 'core-js/modules/es.symbol.js';
import 'core-js/modules/es.array.filter.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.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.regexp.exec.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 React__default, { useReducer } from 'react';
import useDeepCompareEffect from 'use-deep-compare-effect';
import { getRowAction } from './tableUtilities.js';
import { tableReducer } from './tableReducer.js';
import { tableRegister, tablePageChange, tableFilterApply, tableToolbarToggle, tableFilterClear, tableActionCancel, tableActionApply, tableSearchApply, tableAdvancedFiltersToggle, tableAdvancedFiltersRemove, tableAdvancedFiltersApply, tableAdvancedFiltersCancel, tableAdvancedFiltersCreate, tableToggleAggregations, tableColumnSort, tableRowSelect, tableRowSelectAll, tableRowExpand, tableRowLoadMore, tableRowActionError, tableRowActionComplete, tableRowActionStart, tableColumnOrder, tableColumnResize, tableMultiSortToggleModal, tableSaveMultiSortColumns, tableCancelMultiSortColumns, tableClearMultiSortColumns, tableAddMultiSortColumn, tableRemoveMultiSortColumn, tableRowActionEdit } from './tableActionCreators.js';
import Table, { defaultProps } from './Table.js';

var _excluded = ["data", "expandedData"],
  _excluded2 = ["values"],
  _excluded3 = ["node"],
  _excluded4 = ["renderIcon"],
  _excluded5 = ["error"];
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 callbackParent = function callbackParent(callback) {
  for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
    args[_key - 1] = arguments[_key];
  }
  return callback && callback.apply(void 0, args);
};

/** This component shares the exact same prop types as the Table component */
/* eslint-disable react/prop-types */
var StatefulTable = function StatefulTable(_ref) {
  var _view$toolbar, _view$toolbar2, _state$data, _view$pagination, _view$toolbar3;
  var initialData = _ref.data,
    expandedData = _ref.expandedData,
    other = _objectWithoutProperties(_ref, _excluded);
  var _merge2 = _merge({}, defaultProps(_objectSpread({
      data: initialData
    }, other)), other),
    tableId = _merge2.id,
    initialColumns = _merge2.columns,
    _merge2$options = _merge2.options,
    hasUserViewManagement = _merge2$options.hasUserViewManagement,
    hasRowSelection = _merge2$options.hasRowSelection,
    options = _merge2.options,
    _merge2$view = _merge2.view,
    customToolbarContent = _merge2$view.toolbar.customToolbarContent,
    initialTotalItems = _merge2$view.pagination.totalItems,
    initialState = _merge2.view,
    callbackActions = _merge2.actions,
    lightweight = _merge2.lightweight;
  var _useReducer = useReducer(tableReducer, {
      data: initialData,
      view: initialState,
      columns: initialColumns
    }),
    _useReducer2 = _slicedToArray(_useReducer, 2),
    state = _useReducer2[0],
    dispatch = _useReducer2[1];
  var isLoading = get(initialState, 'table.loadingState.isLoading');
  var view = state.view,
    _state$view$table = state.view.table,
    filteredData = _state$view$table.filteredData,
    selectedIds = _state$view$table.selectedIds,
    sort = _state$view$table.sort;
  var pagination = callbackActions.pagination,
    toolbar = callbackActions.toolbar,
    table = callbackActions.table,
    _onUserViewModified = callbackActions.onUserViewModified;
  // Need to initially sort and filter the tables data, but preserve the selectedId.
  useDeepCompareEffect(function () {
    dispatch(tableRegister({
      data: initialData,
      isLoading: isLoading,
      view: initialState,
      totalItems: initialTotalItems || initialData.length,
      hasUserViewManagement: hasUserViewManagement,
      hasRowSelection: hasRowSelection
    }));
  }, [
  // Props of type React.Element or React.Node must not be included in
  // useDeepCompareEffect dependency arrays, their object signature is
  // massive and will throw out of memory errors if compared.
  // https://github.com/kentcdodds/use-deep-compare-effect/issues/7
  // https://twitter.com/dan_abramov/status/1104415855612432384
  initialData.map(function (action) {
    // extract values object from action
    var values = action.values,
      nonElements = _objectWithoutProperties(action, _excluded2);

    // remove element/node from values object
    values.node;
      var nonNodeElements = _objectWithoutProperties(values, _excluded3);

    // combine agin without node/element
    return _objectSpread(_objectSpread({}, nonElements), {}, {
      nonNodeElements: nonNodeElements
    });
  }), isLoading, initialState.pagination, initialState.filters, initialState.advancedFilters, initialState.toolbar.activeBar,
  // Remove the icon as it's a React.Element which can not be compared

  initialState.toolbar.batchActions && initialState.toolbar.batchActions.map(function (action) {
    action.renderIcon;
      var nonElements = _objectWithoutProperties(action, _excluded4);
    return nonElements;
  }), initialState.toolbar.initialDefaultSearch, initialState.toolbar.search, initialState.toolbar.isDisabled, initialState.toolbar.hideClearAllFiltersButton, initialState.table.isSelectAllSelected, initialState.table.isSelectAllIndeterminate, initialState.table.selectedIds, initialState.table.sort, initialState.table.ordering,
  // Remove the error as it's a React.Element/Node which can not be compared
  initialState.table.rowActions && initialState.table.rowActions.map(function (action) {
    action.error;
      var nonElements = _objectWithoutProperties(action, _excluded5);
    return nonElements;
  }), initialState.table.expandedIds, initialState.table.loadingMoreIds, initialState.table.loadingState]);
  var columns = hasUserViewManagement ? state.columns : initialColumns;
  var defaultSearch = (view === null || view === void 0 || (_view$toolbar = view.toolbar) === null || _view$toolbar === void 0 || (_view$toolbar = _view$toolbar.search) === null || _view$toolbar === void 0 ? void 0 : _view$toolbar.defaultValue) || '';
  var initialDefaultSearch = (view === null || view === void 0 || (_view$toolbar2 = view.toolbar) === null || _view$toolbar2 === void 0 ? void 0 : _view$toolbar2.initialDefaultSearch) || '';
  var _ref2 = pagination || {},
    _onChangePage = _ref2.onChangePage;
  var _ref3 = toolbar || {},
    _onApplyFilter = _ref3.onApplyFilter,
    _onToggleFilter = _ref3.onToggleFilter,
    _onShowRowEdit = _ref3.onShowRowEdit,
    _onToggleColumnSelection = _ref3.onToggleColumnSelection,
    _onClearAllFilters = _ref3.onClearAllFilters,
    _onCancelBatchAction = _ref3.onCancelBatchAction,
    _onApplyBatchAction = _ref3.onApplyBatchAction,
    _onApplySearch = _ref3.onApplySearch,
    onDownloadCSV = _ref3.onDownloadCSV,
    _onToggleAdvancedFilter = _ref3.onToggleAdvancedFilter,
    _onRemoveAdvancedFilter = _ref3.onRemoveAdvancedFilter,
    _onApplyAdvancedFilter = _ref3.onApplyAdvancedFilter,
    _onCancelAdvancedFilter = _ref3.onCancelAdvancedFilter,
    _onCreateAdvancedFilter = _ref3.onCreateAdvancedFilter,
    _onToggleAggregations = _ref3.onToggleAggregations,
    _onApplyToolbarAction = _ref3.onApplyToolbarAction,
    _onSearchExpand = _ref3.onSearchExpand;
  var _ref4 = table || {},
    _onChangeSort = _ref4.onChangeSort,
    _onRowSelected = _ref4.onRowSelected,
    _onRowClicked = _ref4.onRowClicked,
    _onSelectAll = _ref4.onSelectAll,
    _onRowExpanded = _ref4.onRowExpanded,
    _onRowLoadMore = _ref4.onRowLoadMore,
    _onApplyRowAction = _ref4.onApplyRowAction,
    _onClearRowError = _ref4.onClearRowError,
    onEmptyStateAction = _ref4.onEmptyStateAction,
    _onChangeOrdering = _ref4.onChangeOrdering,
    _onColumnResize = _ref4.onColumnResize,
    _onOverflowItemClicked = _ref4.onOverflowItemClicked,
    _onSaveMultiSortColumns = _ref4.onSaveMultiSortColumns,
    _onCancelMultiSortColumns = _ref4.onCancelMultiSortColumns,
    _onClearMultiSortColumns = _ref4.onClearMultiSortColumns,
    _onAddMultiSortColumn = _ref4.onAddMultiSortColumn,
    _onRemoveMultiSortColumn = _ref4.onRemoveMultiSortColumn,
    _onFilterRowIconClick = _ref4.onFilterRowIconClick,
    _onDrag = _ref4.onDrag,
    _onDrop = _ref4.onDrop;

  // In addition to updating the store, I always callback to the parent in case they want to do something
  var actions = {
    pagination: {
      onChangePage: function onChangePage(paginationValues) {
        dispatch(tablePageChange(paginationValues));
        callbackParent(_onChangePage, paginationValues);
      }
    },
    toolbar: {
      onApplyFilter: function onApplyFilter(filterValues) {
        dispatch(tableFilterApply(filterValues));
        callbackParent(_onApplyFilter, filterValues);
      },
      onToggleFilter: function onToggleFilter() {
        dispatch(tableToolbarToggle('filter'));
        callbackParent(_onToggleFilter, 'filter');
      },
      onToggleColumnSelection: function onToggleColumnSelection() {
        dispatch(tableToolbarToggle('column'));
        callbackParent(_onToggleColumnSelection, 'column');
      },
      onShowRowEdit: function onShowRowEdit() {
        dispatch(tableToolbarToggle('rowEdit'));
        callbackParent(_onShowRowEdit, 'rowEdit');
      },
      onClearAllFilters: function onClearAllFilters() {
        dispatch(tableFilterClear());
        callbackParent(_onClearAllFilters);
      },
      onCancelBatchAction: function onCancelBatchAction() {
        dispatch(tableActionCancel());
        callbackParent(_onCancelBatchAction);
      },
      onApplyBatchAction: function onApplyBatchAction(id) {
        dispatch(tableActionApply(id));
        callbackParent(_onApplyBatchAction, id, selectedIds);
      },
      onApplySearch: function onApplySearch(string) {
        dispatch(tableSearchApply(string));
        callbackParent(_onApplySearch, string);
      },
      onToggleAdvancedFilter: function onToggleAdvancedFilter() {
        dispatch(tableAdvancedFiltersToggle());
        callbackParent(_onToggleAdvancedFilter);
      },
      onRemoveAdvancedFilter: function onRemoveAdvancedFilter(event, filterId) {
        dispatch(tableAdvancedFiltersRemove(filterId));
        callbackParent(_onRemoveAdvancedFilter);
      },
      onApplyAdvancedFilter: function onApplyAdvancedFilter(filterState) {
        dispatch(tableAdvancedFiltersApply(filterState));
        callbackParent(_onApplyAdvancedFilter);
      },
      onCancelAdvancedFilter: function onCancelAdvancedFilter() {
        dispatch(tableAdvancedFiltersCancel());
        callbackParent(_onCancelAdvancedFilter);
      },
      onCreateAdvancedFilter: function onCreateAdvancedFilter() {
        dispatch(tableAdvancedFiltersCreate());
        callbackParent(_onCreateAdvancedFilter);
      },
      onToggleAggregations: function onToggleAggregations() {
        dispatch(tableToggleAggregations());
        callbackParent(_onToggleAggregations);
      },
      onApplyToolbarAction: function onApplyToolbarAction(action) {
        callbackParent(_onApplyToolbarAction, action);
      },
      onSearchExpand: function onSearchExpand(action) {
        callbackParent(_onSearchExpand, action);
      },
      onDownloadCSV: onDownloadCSV
    },
    table: {
      onDrag: function onDrag(rows) {
        return callbackParent(_onDrag, rows);
      },
      onDrop: function onDrop(dragRowIds, dropRowId) {
        callbackParent(_onDrop, dragRowIds, dropRowId);
      },
      onChangeSort: function onChangeSort(column) {
        var sortDirection = sort ? sort.direction : undefined;
        dispatch(tableColumnSort(column, columns));
        callbackParent(_onChangeSort, column, sortDirection);
      },
      onRowSelected: function onRowSelected(rowId, isSelected, newSelectedIds) {
        dispatch(tableRowSelect(newSelectedIds, options.hasRowSelection));
        // Params rowId & isSelected kept for backwards compatability
        callbackParent(_onRowSelected, rowId, isSelected, newSelectedIds);
      },
      onRowClicked: function onRowClicked(rowId) {
        // This action doesn't update our table state, it's up to the user
        callbackParent(_onRowClicked, rowId);
      },
      onSelectAll: function onSelectAll(isSelected) {
        dispatch(tableRowSelectAll(isSelected));
        callbackParent(_onSelectAll, isSelected);
      },
      onRowExpanded: function onRowExpanded(rowId, isExpanded) {
        var expansionOptions = _typeof(options.hasRowExpansion) === 'object' ? options.hasRowExpansion : {};
        dispatch(tableRowExpand(rowId, isExpanded, null, expansionOptions));
        callbackParent(_onRowExpanded, rowId, isExpanded);
      },
      onRowLoadMore: function onRowLoadMore(rowId) {
        dispatch(tableRowLoadMore(rowId));
        callbackParent(_onRowLoadMore, rowId);
      },
      onApplyRowAction: function () {
        var _onApplyRowAction2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(actionId, rowId) {
          var action;
          return _regeneratorRuntime.wrap(function _callee$(_context) {
            while (1) switch (_context.prev = _context.next) {
              case 0:
                action = state.data && getRowAction(state.data, actionId, rowId);
                dispatch(tableRowActionStart(rowId));
                _context.prev = 2;
                _context.next = 5;
                return callbackParent(_onApplyRowAction, actionId, rowId);
              case 5:
                if (action.isEdit) {
                  dispatch(tableRowActionEdit(rowId));
                }
                dispatch(tableRowActionComplete(rowId));
                _context.next = 12;
                break;
              case 9:
                _context.prev = 9;
                _context.t0 = _context["catch"](2);
                dispatch(tableRowActionError(rowId, _context.t0));
              case 12:
              case "end":
                return _context.stop();
            }
          }, _callee, null, [[2, 9]]);
        }));
        function onApplyRowAction(_x, _x2) {
          return _onApplyRowAction2.apply(this, arguments);
        }
        return onApplyRowAction;
      }(),
      onClearRowError: function onClearRowError(rowId) {
        dispatch(tableRowActionComplete(rowId));
        callbackParent(_onClearRowError, rowId);
      },
      onEmptyStateAction: onEmptyStateAction ? function () {
        return (
          // This action doesn't update our table state, it's up to the user
          callbackParent(onEmptyStateAction)
        );
      } : null,
      onChangeOrdering: function onChangeOrdering(ordering) {
        dispatch(tableColumnOrder(ordering));
        callbackParent(_onChangeOrdering, ordering);
      },
      onColumnResize: function onColumnResize(resizedColumns) {
        // For backwards compatability we only update the state when hasUserViewManagement is active
        if (hasUserViewManagement) {
          dispatch(tableColumnResize(resizedColumns));
        }
        callbackParent(_onColumnResize, resizedColumns);
      },
      onOverflowItemClicked: function onOverflowItemClicked(id, meta) {
        if (id === 'multi-sort') {
          dispatch(tableMultiSortToggleModal(meta));
        }
        callbackParent(_onOverflowItemClicked, id, meta);
      },
      onSaveMultiSortColumns: function onSaveMultiSortColumns(sortColumns) {
        dispatch(tableSaveMultiSortColumns(sortColumns));
        callbackParent(_onSaveMultiSortColumns, sortColumns);
      },
      onCancelMultiSortColumns: function onCancelMultiSortColumns() {
        dispatch(tableCancelMultiSortColumns());
        callbackParent(_onCancelMultiSortColumns);
      },
      onClearMultiSortColumns: function onClearMultiSortColumns() {
        dispatch(tableClearMultiSortColumns());
        callbackParent(_onClearMultiSortColumns);
      },
      onAddMultiSortColumn: function onAddMultiSortColumn(index) {
        dispatch(tableAddMultiSortColumn(index));
        callbackParent(_onAddMultiSortColumn, index);
      },
      onRemoveMultiSortColumn: function onRemoveMultiSortColumn(index) {
        dispatch(tableRemoveMultiSortColumn(index));
        callbackParent(_onRemoveMultiSortColumn, index);
      },
      onFilterRowIconClick: function onFilterRowIconClick(evt) {
        callbackParent(_onFilterRowIconClick, evt);
      }
    },
    onUserViewModified: function onUserViewModified(viewConfiguration) {
      callbackParent(_onUserViewModified, viewConfiguration);
    }
  };
  var filteredCount = (filteredData === null || filteredData === void 0 ? void 0 : filteredData.length) || 0;
  var currentlyLoadedDataCount = ((_state$data = state.data) === null || _state$data === void 0 ? void 0 : _state$data.length) || 0;
  var filteredTotalItems = filteredCount && filteredCount !== currentlyLoadedDataCount ? filteredCount : (view === null || view === void 0 || (_view$pagination = view.pagination) === null || _view$pagination === void 0 ? void 0 : _view$pagination.totalItems) || initialTotalItems || currentlyLoadedDataCount;
  return filteredData ? /*#__PURE__*/React__default.createElement(Table, _extends({}, other, {
    // need to passthrough all other props
    id: tableId,
    columns: columns,
    data: filteredData,
    expandedData: expandedData,
    options: options,
    view: _objectSpread(_objectSpread({}, view), {}, {
      toolbar: _objectSpread(_objectSpread({}, view === null || view === void 0 ? void 0 : view.toolbar), {}, {
        search: _objectSpread(_objectSpread({}, view === null || view === void 0 || (_view$toolbar3 = view.toolbar) === null || _view$toolbar3 === void 0 ? void 0 : _view$toolbar3.search), {}, {
          defaultValue: defaultSearch
        }),
        customToolbarContent: customToolbarContent,
        initialDefaultSearch: initialDefaultSearch
      }),
      pagination: _objectSpread(_objectSpread({}, view.pagination), {}, {
        totalItems: filteredTotalItems
      })
    }),
    actions: actions,
    lightweight: lightweight
  })) : null;
};
StatefulTable.__docgenInfo = {
  "description": "This component shares the exact same prop types as the Table component",
  "methods": [],
  "displayName": "StatefulTable"
};
var StatefulTable$1 = StatefulTable;

export { StatefulTable$1 as default };
