'use strict';

var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var _extends = require('@babel/runtime/helpers/extends');
var _objectWithoutProperties = require('@babel/runtime/helpers/objectWithoutProperties');
require('core-js/modules/es.array.concat.js');
require('core-js/modules/es.array.map.js');
require('core-js/modules/es.array.slice.js');
require('core-js/modules/es.regexp.exec.js');
require('core-js/modules/es.string.replace.js');
var React = require('react');
var PropTypes = require('prop-types');
var react = require('@carbon/react');
var classnames = require('classnames');
var Settings = require('../../constants/Settings.js');
var UseResizeObserver = require('../../internal/UseResizeObserver.js');
var iconsReact = require('@carbon/icons-react');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var _defineProperty__default = /*#__PURE__*/_interopDefault(_defineProperty);
var _toConsumableArray__default = /*#__PURE__*/_interopDefault(_toConsumableArray);
var _slicedToArray__default = /*#__PURE__*/_interopDefault(_slicedToArray);
var _extends__default = /*#__PURE__*/_interopDefault(_extends);
var _objectWithoutProperties__default = /*#__PURE__*/_interopDefault(_objectWithoutProperties);
var React__default = /*#__PURE__*/_interopDefault(React);
var PropTypes__default = /*#__PURE__*/_interopDefault(PropTypes);
var classnames__default = /*#__PURE__*/_interopDefault(classnames);

var _excluded = ["children", "i18n"],
  _excluded2 = ["filterTagsOverflowMenuText"];
var DEFAULT_OVERFLOW_TEXT = 'More: {n}';
var getFilterTagsOverflowText = function getFilterTagsOverflowText(filterCount, i18nProp) {
  if (typeof i18nProp === 'function') {
    return i18nProp(filterCount);
  }
  return i18nProp.replace('{n}', filterCount);
};
var prefix = Settings.settings.prefix,
  iotPrefix = Settings.settings.iotPrefix;
/* eslint-disable-next-line react/prop-types */
var DefaultWrapper = /*#__PURE__*/React__default.default.forwardRef(function (_ref, ref) {
  var children = _ref.children;
    _ref.i18n;
    var props = _objectWithoutProperties__default.default(_ref, _excluded);
  return /*#__PURE__*/React__default.default.createElement("div", _extends__default.default({}, props, {
    ref: ref
  }), children);
});
/* eslint-disable-next-line react/prop-types */
var OverflowTag = function OverflowTag(_ref2) {
  var children = _ref2.children;
  return /*#__PURE__*/React__default.default.createElement("div", {
    className: "".concat(iotPrefix, "--filtertags-overflow-item__wrapper")
  }, /*#__PURE__*/React__default.default.createElement("span", null, children), /*#__PURE__*/React__default.default.createElement(iconsReact.Close, null));
};
var FilterTags = function FilterTags(_ref3) {
  var _overFlowContainerRef3, _overFlowContainerRef4;
  var children = _ref3.children,
    hasOverflow = _ref3.hasOverflow,
    id = _ref3.id,
    tagContainer = _ref3.tagContainer,
    onChange = _ref3.onChange,
    i18nProps = _ref3.i18n,
    testId = _ref3.testId;
  var TagContainer = tagContainer || DefaultWrapper;
  var overFlowContainerRef = React.useRef(null);
  UseResizeObserver.useResize(overFlowContainerRef);
  var childrenItems = React.Children.map(children, function (child) {
    return child;
  });
  var breakingWidth = React.useRef([]);
  var _useState = React.useState([]),
    _useState2 = _slicedToArray__default.default(_useState, 2),
    overflowItems = _useState2[0],
    setOverflowItems = _useState2[1];
  var _useState3 = React.useState(childrenItems),
    _useState4 = _slicedToArray__default.default(_useState3, 2),
    visibleItems = _useState4[0],
    setVisibleItems = _useState4[1];
  var _i18nProps$filterTags = i18nProps.filterTagsOverflowMenuText,
    filterTagsOverflowMenuText = _i18nProps$filterTags === void 0 ? DEFAULT_OVERFLOW_TEXT : _i18nProps$filterTags,
    i18n = _objectWithoutProperties__default.default(i18nProps, _excluded2);
  React.useEffect(function () {
    if (hasOverflow && overFlowContainerRef) {
      setOverflowItems([]);
      setVisibleItems(childrenItems.slice(0));
    }
  },
  // eslint-disable-next-line react-hooks/exhaustive-deps
  [children]);
  React.useLayoutEffect(function () {
    if (hasOverflow && overFlowContainerRef.current) {
      var _overFlowContainerRef, _overFlowContainerRef2;
      var clientWidth = (_overFlowContainerRef = overFlowContainerRef.current) === null || _overFlowContainerRef === void 0 ? void 0 : _overFlowContainerRef.clientWidth;
      var scrollWidth = (_overFlowContainerRef2 = overFlowContainerRef.current) === null || _overFlowContainerRef2 === void 0 ? void 0 : _overFlowContainerRef2.scrollWidth;
      var currBreakingWidth = breakingWidth.current;
      var breakingWidthLength = currBreakingWidth.length;
      var tooBig = scrollWidth > clientWidth;
      if (tooBig) {
        currBreakingWidth.push(scrollWidth);
        if (visibleItems.length > 1) {
          // Move item to the hidden list
          setOverflowItems([visibleItems.pop()].concat(_toConsumableArray__default.default(overflowItems)));
          setVisibleItems(_toConsumableArray__default.default(visibleItems));
        }
      } else if (currBreakingWidth[breakingWidthLength - 1] >= 0 && clientWidth > currBreakingWidth[breakingWidthLength - 1] && overflowItems.length > 0) {
        // Move the item to the visible list
        setVisibleItems([].concat(_toConsumableArray__default.default(visibleItems), [overflowItems.shift()]));
        setOverflowItems(_toConsumableArray__default.default(overflowItems));
        currBreakingWidth.shift();
      }
    }
  } /* eslint-disable react-hooks/exhaustive-deps */, [overFlowContainerRef === null || overFlowContainerRef === void 0 || (_overFlowContainerRef3 = overFlowContainerRef.current) === null || _overFlowContainerRef3 === void 0 ? void 0 : _overFlowContainerRef3.scrollWidth, overFlowContainerRef === null || overFlowContainerRef === void 0 || (_overFlowContainerRef4 = overFlowContainerRef.current) === null || _overFlowContainerRef4 === void 0 ? void 0 : _overFlowContainerRef4.clientWidth, childrenItems]
  /* eslint-enable react-hooks/exhaustive-deps */);
  return /*#__PURE__*/React__default.default.createElement(TagContainer, {
    key: "".concat(hasOverflow, "-Tag-Container"),
    id: id
    // TODO: remove id in v3
    ,
    "data-testid": id || testId,
    className: classnames__default.default("".concat(iotPrefix, "--filtertags-container"), _defineProperty__default.default({}, "".concat(iotPrefix, "--filtertags-container__wrap"), hasOverflow)),
    ref: overFlowContainerRef,
    onChange: onChange,
    i18n: i18n
  }, visibleItems, overflowItems.length > 0 && /*#__PURE__*/React__default.default.createElement(react.OverflowMenu, {
    "data-floating-menu-container": true,
    className: "".concat(iotPrefix, "--filtertags-overflow-menu"),
    renderIcon: function renderIcon() {
      return /*#__PURE__*/React__default.default.createElement("div", {
        className: "".concat(prefix, "--tag")
      }, getFilterTagsOverflowText(overflowItems.length, filterTagsOverflowMenuText));
    },
    menuOptionsClass: "".concat(iotPrefix, "--filtertags-overflow-items"),
    menuOffset: {
      top: 15
    },
    "data-testid": "".concat(testId, "-overflow-menu")
  }, overflowItems.map(function (child, i) {
    return /*#__PURE__*/React__default.default.createElement(react.OverflowMenuItem, {
      "data-testid": "".concat(testId, "-overflow-menu-item-").concat(i),
      className: "".concat(iotPrefix, "--filtertags-overflow-item"),
      title: child.props.children,
      key: "".concat(child.props.children, "-").concat(i),
      onClick: child.props.onClose,
      itemText: /*#__PURE__*/React__default.default.createElement(OverflowTag, null, child.props.children)
    });
  })));
};
var propTypes = {
  /**
   * ID for filter tag container
   */
  id: PropTypes__default.default.string,
  /**
   * Tag components nested inside Filter tag component
   */
  children: PropTypes__default.default.node.isRequired,
  /**
   * Bit to determine if tags collapse into overflow tag
   */
  hasOverflow: PropTypes__default.default.bool,
  /**
   * Optional container for filter tags
   */
  tagContainer: PropTypes__default.default.elementType,
  /**
   * OnChange handled passed to the tagContainer
   */
  onChange: PropTypes__default.default.func,
  /**
   * This is an object of {[key: string]: string}, but it's
   * unknown what they are as it's dependent on the tagContainer
   */
  // eslint-disable-next-line react/forbid-prop-types
  i18n: PropTypes__default.default.object,
  testId: PropTypes__default.default.string
};
var defaultProps = {
  id: 'filter-tag-container',
  hasOverflow: true,
  tagContainer: null,
  onChange: null,
  i18n: {
    filterTagsOverflowMenuText: DEFAULT_OVERFLOW_TEXT
  },
  testId: 'filter-tags'
};
FilterTags.propTypes = propTypes;
FilterTags.defaultProps = defaultProps;
FilterTags.__docgenInfo = {
  "description": "",
  "methods": [],
  "displayName": "FilterTags",
  "props": {
    "id": {
      "defaultValue": {
        "value": "'filter-tag-container'",
        "computed": false
      },
      "description": "ID for filter tag container",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "hasOverflow": {
      "defaultValue": {
        "value": "true",
        "computed": false
      },
      "description": "Bit to determine if tags collapse into overflow tag",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "tagContainer": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "description": "Optional container for filter tags",
      "type": {
        "name": "elementType"
      },
      "required": false
    },
    "onChange": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "description": "OnChange handled passed to the tagContainer",
      "type": {
        "name": "func"
      },
      "required": false
    },
    "i18n": {
      "defaultValue": {
        "value": "{\n  filterTagsOverflowMenuText: DEFAULT_OVERFLOW_TEXT,\n}",
        "computed": false
      },
      "description": "This is an object of {[key: string]: string}, but it's\nunknown what they are as it's dependent on the tagContainer",
      "type": {
        "name": "object"
      },
      "required": false
    },
    "testId": {
      "defaultValue": {
        "value": "'filter-tags'",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "children": {
      "description": "Tag components nested inside Filter tag component",
      "type": {
        "name": "node"
      },
      "required": true
    }
  }
};
var FilterTags$1 = FilterTags;

module.exports = FilterTags$1;
