import _slicedToArray from "@babel/runtime-corejs3/helpers/slicedToArray";
import _extends from "@babel/runtime-corejs3/helpers/extends";
import _toConsumableArray from "@babel/runtime-corejs3/helpers/toConsumableArray";
import _concatInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/concat";
import _mapInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/map";
import _findInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/find";
import _filterInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/filter";
import _findIndexInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/find-index";
import * as React from 'react';
import { getColumnPos, renderColumnTitle, getColumnKey } from '../../util';
import FilterDropdown from './FilterDropdown';

function collectFilterStates(columns, init, pos) {
  var filterStates = [];
  (columns || []).forEach(function (column, index) {
    var columnPos = getColumnPos(index, pos);

    if ('children' in column) {
      var _context;

      filterStates = _concatInstanceProperty(_context = []).call(_context, _toConsumableArray(filterStates), _toConsumableArray(collectFilterStates(column.children, init, columnPos)));
    } else if (column.filters || 'filterDropdown' in column || 'onFilter' in column) {
      if ('filteredValue' in column) {
        // Controlled
        filterStates.push({
          column: column,
          key: getColumnKey(column, columnPos),
          filteredKeys: column.filteredValue,
          forceFiltered: column.filtered
        });
      } else {
        // Uncontrolled
        filterStates.push({
          column: column,
          key: getColumnKey(column, columnPos),
          filteredKeys: init && column.defaultFilteredValue ? column.defaultFilteredValue : undefined,
          forceFiltered: column.filtered
        });
      }
    }
  });
  return filterStates;
}

function injectFilter(prefixCls, dropdownPrefixCls, columns, filterStates, triggerFilter, getPopupContainer, locale, pos) {
  return _mapInstanceProperty(columns).call(columns, function (column, index) {
    var columnPos = getColumnPos(index, pos);
    var _column$filterMultipl = column.filterMultiple,
        filterMultiple = _column$filterMultipl === void 0 ? true : _column$filterMultipl;

    if (column.filters || 'filterDropdown' in column) {
      var columnKey = getColumnKey(column, columnPos);

      var filterState = _findInstanceProperty(filterStates).call(filterStates, function (_ref) {
        var key = _ref.key;
        return columnKey === key;
      });

      return _extends(_extends({}, column), {
        title: function title(renderProps) {
          return /*#__PURE__*/React.createElement(FilterDropdown, {
            prefixCls: "".concat(prefixCls, "-filter"),
            dropdownPrefixCls: dropdownPrefixCls,
            column: column,
            columnKey: columnKey,
            filterState: filterState,
            filterMultiple: filterMultiple,
            triggerFilter: triggerFilter,
            locale: locale,
            getPopupContainer: getPopupContainer
          }, renderColumnTitle(column.title, renderProps));
        }
      });
    }

    if ('children' in column) {
      return _extends(_extends({}, column), {
        children: injectFilter(prefixCls, dropdownPrefixCls, column.children, filterStates, triggerFilter, getPopupContainer, locale, columnPos)
      });
    }

    return column;
  });
}

function generateFilterInfo(filterStates) {
  var currentFilters = {};
  filterStates.forEach(function (_ref2) {
    var key = _ref2.key,
        filteredKeys = _ref2.filteredKeys;
    currentFilters[key] = filteredKeys || null;
  });
  return currentFilters;
}

function flattenKeys(filters) {
  var keys = [];
  (filters || []).forEach(function (_ref3) {
    var value = _ref3.value,
        children = _ref3.children;
    keys.push(value);

    if (children) {
      var _context2;

      keys = _concatInstanceProperty(_context2 = []).call(_context2, _toConsumableArray(keys), _toConsumableArray(flattenKeys(children)));
    }
  });
  return keys;
}

export function getFilterData(data, filterStates) {
  return filterStates.reduce(function (currentData, filterState) {
    var _filterState$column = filterState.column,
        onFilter = _filterState$column.onFilter,
        filters = _filterState$column.filters,
        filteredKeys = filterState.filteredKeys;

    if (onFilter && filteredKeys && filteredKeys.length) {
      return _filterInstanceProperty(currentData).call(currentData, function (record) {
        return filteredKeys.some(function (key) {
          var keys = flattenKeys(filters);

          var keyIndex = _findIndexInstanceProperty(keys).call(keys, function (k) {
            return String(k) === String(key);
          });

          var realKey = keyIndex !== -1 ? keys[keyIndex] : key;
          return onFilter(realKey, record);
        });
      });
    }

    return currentData;
  }, data);
}

function useFilter(_ref4) {
  var prefixCls = _ref4.prefixCls,
      dropdownPrefixCls = _ref4.dropdownPrefixCls,
      mergedColumns = _ref4.mergedColumns,
      onFilterChange = _ref4.onFilterChange,
      getPopupContainer = _ref4.getPopupContainer,
      tableLocale = _ref4.locale;

  var _React$useState = React.useState(collectFilterStates(mergedColumns, true)),
      _React$useState2 = _slicedToArray(_React$useState, 2),
      filterStates = _React$useState2[0],
      setFilterStates = _React$useState2[1];

  var mergedFilterStates = React.useMemo(function () {
    var collectedStates = collectFilterStates(mergedColumns, false); // Return if not controlled

    if (collectedStates.every(function (_ref5) {
      var filteredKeys = _ref5.filteredKeys;
      return filteredKeys === undefined;
    })) {
      return filterStates;
    }

    return collectedStates;
  }, [mergedColumns, filterStates]);
  var getFilters = React.useCallback(function () {
    return generateFilterInfo(mergedFilterStates);
  }, [mergedFilterStates]);

  var triggerFilter = function triggerFilter(filterState) {
    var newFilterStates = _filterInstanceProperty(mergedFilterStates).call(mergedFilterStates, function (_ref6) {
      var key = _ref6.key;
      return key !== filterState.key;
    });

    newFilterStates.push(filterState);
    setFilterStates(newFilterStates);
    onFilterChange(generateFilterInfo(newFilterStates), newFilterStates);
  };

  var transformColumns = function transformColumns(innerColumns) {
    return injectFilter(prefixCls, dropdownPrefixCls, innerColumns, mergedFilterStates, triggerFilter, getPopupContainer, tableLocale);
  };

  return [transformColumns, mergedFilterStates, getFilters];
}

export default useFilter;