"use strict";

var _typeof = require("@babel/runtime-corejs3/helpers/typeof");

var _WeakMap = require("@babel/runtime-corejs3/core-js-stable/weak-map");

var _Object$getOwnPropertyDescriptor = require("@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptor");

var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getFilterData = getFilterData;
exports["default"] = void 0;

var _concat = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/concat"));

var _map = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/map"));

var _find = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/find"));

var _filter = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/filter"));

var _findIndex = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/find-index"));

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/slicedToArray"));

var _extends2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/extends"));

var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/toConsumableArray"));

var React = _interopRequireWildcard(require("react"));

var _util = require("../../util");

var _FilterDropdown = _interopRequireDefault(require("./FilterDropdown"));

function _getRequireWildcardCache(nodeInterop) { if (typeof _WeakMap !== "function") return null; var cacheBabelInterop = new _WeakMap(); var cacheNodeInterop = new _WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && _Object$getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? _Object$getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

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

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

      filterStates = (0, _concat["default"])(_context = []).call(_context, (0, _toConsumableArray2["default"])(filterStates), (0, _toConsumableArray2["default"])(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: (0, _util.getColumnKey)(column, columnPos),
          filteredKeys: column.filteredValue,
          forceFiltered: column.filtered
        });
      } else {
        // Uncontrolled
        filterStates.push({
          column: column,
          key: (0, _util.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 (0, _map["default"])(columns).call(columns, function (column, index) {
    var columnPos = (0, _util.getColumnPos)(index, pos);
    var _column$filterMultipl = column.filterMultiple,
        filterMultiple = _column$filterMultipl === void 0 ? true : _column$filterMultipl;

    if (column.filters || 'filterDropdown' in column) {
      var columnKey = (0, _util.getColumnKey)(column, columnPos);
      var filterState = (0, _find["default"])(filterStates).call(filterStates, function (_ref) {
        var key = _ref.key;
        return columnKey === key;
      });
      return (0, _extends2["default"])((0, _extends2["default"])({}, column), {
        title: function title(renderProps) {
          return /*#__PURE__*/React.createElement(_FilterDropdown["default"], {
            prefixCls: "".concat(prefixCls, "-filter"),
            dropdownPrefixCls: dropdownPrefixCls,
            column: column,
            columnKey: columnKey,
            filterState: filterState,
            filterMultiple: filterMultiple,
            triggerFilter: triggerFilter,
            locale: locale,
            getPopupContainer: getPopupContainer
          }, (0, _util.renderColumnTitle)(column.title, renderProps));
        }
      });
    }

    if ('children' in column) {
      return (0, _extends2["default"])((0, _extends2["default"])({}, 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 = (0, _concat["default"])(_context2 = []).call(_context2, (0, _toConsumableArray2["default"])(keys), (0, _toConsumableArray2["default"])(flattenKeys(children)));
    }
  });
  return keys;
}

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 (0, _filter["default"])(currentData).call(currentData, function (record) {
        return filteredKeys.some(function (key) {
          var keys = flattenKeys(filters);
          var keyIndex = (0, _findIndex["default"])(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 = (0, _slicedToArray2["default"])(_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 = (0, _filter["default"])(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];
}

var _default = useFilter;
exports["default"] = _default;