import _extends from '@babel/runtime/helpers/extends';
import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
import _objectWithoutProperties from '@babel/runtime/helpers/objectWithoutProperties';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import 'core-js/modules/es.symbol.js';
import 'core-js/modules/es.array.concat.js';
import 'core-js/modules/es.array.filter.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 React__default, { useState, useEffect, useCallback } from 'react';
import PropTypes from 'prop-types';
import { TableToolbarSearch as TableToolbarSearch$2 } from '@carbon/react';
import classnames from 'classnames';
import { settings } from '../../../constants/Settings.js';
import { tableTranslateWithId, handleSpecificKeyDown } from '../../../utils/componentUtilityFunctions.js';
import { TableSearchPropTypes, defaultI18NPropTypes } from '../TablePropTypes.js';

var _excluded = ["isExpanded", "onExpand"];
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 iotPrefix = settings.iotPrefix;
var propTypes = {
  /** id of table */
  tableId: PropTypes.string.isRequired,
  /** global table options */
  options: PropTypes.shape({
    /** If true, search is applied as typed. If false, only after 'Enter' is pressed */
    hasFastSearch: PropTypes.bool,
    // True if use can save/load views
    hasUserViewManagement: PropTypes.bool
  }).isRequired,
  /** internationalized labels */
  i18n: PropTypes.shape({
    clearAllFilters: PropTypes.string,
    columnSelectionButtonAria: PropTypes.string,
    filterButtonAria: PropTypes.string,
    editButtonAria: PropTypes.string,
    searchLabel: PropTypes.string,
    searchPlaceholder: PropTypes.string,
    batchCancel: PropTypes.string,
    itemsSelected: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
    itemSelected: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
    filterNone: PropTypes.string,
    filterAscending: PropTypes.string,
    filterDescending: PropTypes.string,
    toggleAggregations: PropTypes.string,
    toolbarLabelAria: PropTypes.string,
    rowCountInHeader: PropTypes.func,
    downloadIconDescription: PropTypes.string,
    /** aria-label applied to the tooltip in the toolbar (if given) */
    toolbarTooltipLabel: PropTypes.string,
    /** button label for batch action overflow menu */
    batchActionsOverflowMenuText: PropTypes.string,
    /** I18N label for search icon in toolbar */
    toolbarSearchIconDescription: PropTypes.string
  }),
  /**
   * Action callbacks to update tableState
   */
  actions: PropTypes.shape({
    onApplySearch: PropTypes.func,
    onSearchExpand: PropTypes.func
  }).isRequired,
  /**
   * Inbound tableState
   */
  tableState: PropTypes.shape({
    /** is the toolbar currently disabled */
    isDisabled: PropTypes.bool,
    search: TableSearchPropTypes
  }).isRequired,
  testId: PropTypes.string,
  langDir: PropTypes.oneOf(['ltr', 'rtl']),
  tooltipAlignment: PropTypes.oneOf(['start', 'center', 'end'])
};
var defaultProps = {
  i18n: _objectSpread({}, defaultI18NPropTypes),
  testId: '',
  langDir: 'ltr',
  tooltipAlignment: 'center'
};
var TableToolbarSearch = function TableToolbarSearch(_ref) {
  var tableId = _ref.tableId,
    i18n = _ref.i18n,
    _ref$options = _ref.options,
    hasFastSearch = _ref$options.hasFastSearch,
    hasUserViewManagement = _ref$options.hasUserViewManagement,
    _ref$actions = _ref.actions,
    onApplySearch = _ref$actions.onApplySearch,
    onSearchExpand = _ref$actions.onSearchExpand,
    _ref$tableState = _ref.tableState,
    searchProp = _ref$tableState.search,
    isDisabled = _ref$tableState.isDisabled,
    testId = _ref.testId,
    langDir = _ref.langDir,
    tooltipAlignment = _ref.tooltipAlignment;
  /* istanbul ignore next */
  var _ref2 = searchProp !== null && searchProp !== void 0 ? searchProp : {},
    searchIsExpanded = _ref2.isExpanded,
    _onExpand = _ref2.onExpand,
    search = _objectWithoutProperties(_ref2, _excluded);

  /**
   * Needed to force update component if search input is cleared from outside of TableToolbar
   * Reference: https://reactjs.org/docs/hooks-faq.html#is-there-something-like-forceupdate
   */
  var _useState = useState(0),
    _useState2 = _slicedToArray(_useState, 2),
    forceRenderCount = _useState2[0],
    setForceRenderCount = _useState2[1];
  var _useState3 = useState(false),
    _useState4 = _slicedToArray(_useState3, 2),
    showSearchTooltip = _useState4[0],
    setShowSearchTooltip = _useState4[1];
  var _useState5 = useState(tooltipAlignment),
    _useState6 = _slicedToArray(_useState5, 2),
    adjustedTooltipAlignment = _useState6[0],
    setAdjustedTooltipAlignment = _useState6[1];
  useEffect(function () {
    var _document$activeEleme;
    /* istanbul ignore else */
    if (((_document$activeEleme = document.activeElement) === null || _document$activeEleme === void 0 ? void 0 : _document$activeEleme.tagName) === 'INPUT') {
      return;
    }
    setForceRenderCount(function (prevValue) {
      return prevValue + 1;
    });
  }, [search.defaultValue]);

  /* istanbul ignore next */
  var handleSearchMouseEnter = useCallback(function () {
    setShowSearchTooltip(true);
  }, []);

  /* istanbul ignore next */
  var handleSearchMouseLeave = useCallback(function () {
    setShowSearchTooltip(false);
  }, []);
  return /*#__PURE__*/React__default.createElement("div", {
    className: "".concat(iotPrefix, "--table-toolbar__search-wrapper")
  }, /*#__PURE__*/React__default.createElement(TableToolbarSearch$2, _extends({}, search, {
    onPointerEnter: handleSearchMouseEnter,
    onPointerLeave: handleSearchMouseLeave,
    key:
    // If hasUserViewManagement is active the whole table is regenerated when a new
    // view is loaded so we probably don't need this key-gen fix to preset a search text.
    // The userViewManagement also needs to be able to set the search.defaultValue
    // while typing without loosing input focus.
    hasUserViewManagement ? "table-toolbar-search-".concat(forceRenderCount) : "table-toolbar-search-user-view-".concat(forceRenderCount),
    defaultValue: search.defaultValue || search.value,
    className: "table-toolbar-search",
    translateWithId: function translateWithId() {
      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }
      return tableTranslateWithId.apply(void 0, [i18n].concat(args));
    },
    id: "".concat(tableId, "-toolbar-search"),
    onChange: function onChange(event, defaultValue) {
      var _event$target;
      var value = (event === null || event === void 0 || (_event$target = event.target) === null || _event$target === void 0 ? void 0 : _event$target.value) || (defaultValue !== null && defaultValue !== void 0 ? defaultValue : '');
      /* istanbul ignore else */
      if (hasFastSearch) {
        onApplySearch(value);
      }
    },
    onKeyDown: hasFastSearch ? undefined : handleSpecificKeyDown(['Enter'], function (e) {
      return onApplySearch(e.target.value);
    }),
    onClear: function onClear() {
      return onApplySearch('');
    },
    onBlur: !hasFastSearch ? function (e, handleExpand) {
      var value = e.target.value;
      onApplySearch(value);
      if (!value) {
        handleExpand(e, false);
      }
    } : undefined,
    disabled: isDisabled
    // TODO: remove deprecated 'testID' in v3
    ,
    "data-testid": "".concat(testId, "-search"),
    expanded: searchIsExpanded || undefined,
    onExpand: function onExpand() {
      for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
        args[_key2] = arguments[_key2];
      }
      /* istanbul ignore if */
      if (_onExpand) _onExpand(args); // Deprecated callback
      /* istanbul ignore else */
      if (onSearchExpand) onSearchExpand(args);
    }
  })), /*#__PURE__*/React__default.createElement("div", {
    className: classnames("".concat(iotPrefix, "--table-toolbar__search-tooltip"), "".concat(iotPrefix, "--table-toolbar__search-tooltip--").concat(adjustedTooltipAlignment), _defineProperty({}, "".concat(iotPrefix, "--table-toolbar__search-tooltip--hide"), !showSearchTooltip)),
    ref: function ref(node) {
      /* istanbul ignore if */
      if (node && node.parentNode) {
        var tooltipRect = node.getBoundingClientRect();
        var toolbarRect = node.parentNode.parentNode.getBoundingClientRect();
        /* istanbul ignore else */
        if (langDir === 'ltr' && tooltipRect.left + tooltipRect.width > toolbarRect.left + toolbarRect.width) {
          setAdjustedTooltipAlignment('end');
          return;
        }
        /* istanbul ignore if */
        if (langDir === 'rtl' && tooltipRect.left < toolbarRect.left) {
          setAdjustedTooltipAlignment('start');
        }
      }
    }
  }, i18n.toolbarSearchIconDescription));
};
TableToolbarSearch.propTypes = propTypes;
TableToolbarSearch.defaultProps = defaultProps;
TableToolbarSearch.__docgenInfo = {
  "description": "",
  "methods": [],
  "displayName": "TableToolbarSearch",
  "props": {
    "i18n": {
      "defaultValue": {
        "value": "{\n  ...defaultI18NPropTypes,\n}",
        "computed": false
      },
      "description": "internationalized labels",
      "type": {
        "name": "shape",
        "value": {
          "clearAllFilters": {
            "name": "string",
            "required": false
          },
          "columnSelectionButtonAria": {
            "name": "string",
            "required": false
          },
          "filterButtonAria": {
            "name": "string",
            "required": false
          },
          "editButtonAria": {
            "name": "string",
            "required": false
          },
          "searchLabel": {
            "name": "string",
            "required": false
          },
          "searchPlaceholder": {
            "name": "string",
            "required": false
          },
          "batchCancel": {
            "name": "string",
            "required": false
          },
          "itemsSelected": {
            "name": "union",
            "value": [{
              "name": "string"
            }, {
              "name": "func"
            }],
            "required": false
          },
          "itemSelected": {
            "name": "union",
            "value": [{
              "name": "string"
            }, {
              "name": "func"
            }],
            "required": false
          },
          "filterNone": {
            "name": "string",
            "required": false
          },
          "filterAscending": {
            "name": "string",
            "required": false
          },
          "filterDescending": {
            "name": "string",
            "required": false
          },
          "toggleAggregations": {
            "name": "string",
            "required": false
          },
          "toolbarLabelAria": {
            "name": "string",
            "required": false
          },
          "rowCountInHeader": {
            "name": "func",
            "required": false
          },
          "downloadIconDescription": {
            "name": "string",
            "required": false
          },
          "toolbarTooltipLabel": {
            "name": "string",
            "description": "aria-label applied to the tooltip in the toolbar (if given)",
            "required": false
          },
          "batchActionsOverflowMenuText": {
            "name": "string",
            "description": "button label for batch action overflow menu",
            "required": false
          },
          "toolbarSearchIconDescription": {
            "name": "string",
            "description": "I18N label for search icon in toolbar",
            "required": false
          }
        }
      },
      "required": false
    },
    "testId": {
      "defaultValue": {
        "value": "''",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "langDir": {
      "defaultValue": {
        "value": "'ltr'",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "enum",
        "value": [{
          "value": "'ltr'",
          "computed": false
        }, {
          "value": "'rtl'",
          "computed": false
        }]
      },
      "required": false
    },
    "tooltipAlignment": {
      "defaultValue": {
        "value": "'center'",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "enum",
        "value": [{
          "value": "'start'",
          "computed": false
        }, {
          "value": "'center'",
          "computed": false
        }, {
          "value": "'end'",
          "computed": false
        }]
      },
      "required": false
    },
    "tableId": {
      "description": "id of table",
      "type": {
        "name": "string"
      },
      "required": true
    },
    "options": {
      "description": "global table options",
      "type": {
        "name": "shape",
        "value": {
          "hasFastSearch": {
            "name": "bool",
            "description": "If true, search is applied as typed. If false, only after 'Enter' is pressed",
            "required": false
          },
          "hasUserViewManagement": {
            "name": "bool",
            "required": false
          }
        }
      },
      "required": true
    },
    "actions": {
      "description": "Action callbacks to update tableState",
      "type": {
        "name": "shape",
        "value": {
          "onApplySearch": {
            "name": "func",
            "required": false
          },
          "onSearchExpand": {
            "name": "func",
            "required": false
          }
        }
      },
      "required": true
    },
    "tableState": {
      "description": "Inbound tableState",
      "type": {
        "name": "shape",
        "value": {
          "isDisabled": {
            "name": "bool",
            "description": "is the toolbar currently disabled",
            "required": false
          },
          "search": {
            "name": "custom",
            "raw": "TableSearchPropTypes",
            "required": false
          }
        }
      },
      "required": true
    }
  }
};
var TableToolbarSearch$1 = TableToolbarSearch;

export { TableToolbarSearch$1 as default };
