"use strict";

exports.__esModule = true;
exports.useFiltersSyncProps = void 0;
var _react = require("react");
var _ToolbarCollectionContext = require("../ToolbarCollectionContext");
function hasFilter(e, index) {
  var _e$props;
  const filter = e == null || (_e$props = e.props) == null ? void 0 : _e$props.filter;
  if (process.env.NODE_ENV !== 'production') {
    if (filter == null) {
      console.warn(`filter component must pass \`filter\` prop directly, missing from CollectionToolbarFilters.children[${index}].props`);
    }
  }
  return filter != null;
}
function flattenChildren(children) {
  const currentChildren = [];
  if (Array.isArray(children)) {
    currentChildren.push(...children);
  } else {
    currentChildren.push(children);
  }
  return currentChildren;
}
function filterValidChildren(children) {
  return _react.Children.toArray(children).filter(hasFilter);
}
function addTagsFilter(children, state) {
  var _state$tagsCollection;
  const tagsFilter = (_state$tagsCollection = state.tagsCollectionState) == null ? void 0 : _state$tagsCollection.buildTagsFilterWrapper();
  if (tagsFilter && !children.some(child => child.props.filter.name === tagsFilter.props.filter.name)) {
    return [...children, tagsFilter];
  }
  return children;
}
function addCustomFieldFilters(children, state) {
  var _state$collectionData;
  const customFieldFilters = (_state$collectionData = state.collectionDataExtension) == null ? void 0 : _state$collectionData.dataExtension.filterableCustomFields.map(customField => {
    var _state$collectionData2;
    if (children.some(child => child.props.filter.name === customField.id)) {
      return null;
    }
    return (_state$collectionData2 = state.collectionDataExtension) == null ? void 0 : _state$collectionData2.buildCustomFieldFilterWrapper(customField);
  }).filter(Boolean);
  if (customFieldFilters) {
    return [...children, ...customFieldFilters];
  }
  return children;
}
const useFiltersSyncProps = children => {
  const state = (0, _ToolbarCollectionContext.useToolbarCollectionContext)();
  const allChildren = flattenChildren(children);
  const filteredChildren = filterValidChildren(allChildren);
  const childrenWithTagsFilter = addTagsFilter(filteredChildren, state);
  const finalChildren = addCustomFieldFilters(childrenWithTagsFilter, state);
  return finalChildren;
};
exports.useFiltersSyncProps = useFiltersSyncProps;
//# sourceMappingURL=useFiltersSyncProps.js.map