"use strict";

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

var _react = _interopRequireDefault(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _reactAutosuggest = _interopRequireDefault(require("react-autosuggest"));

var _deburr = _interopRequireDefault(require("lodash/deburr"));

var _match = _interopRequireDefault(require("autosuggest-highlight/match"));

var _parse = _interopRequireDefault(require("autosuggest-highlight/parse"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

function getSuggestions(value, suggestions) {
  var inputValue = (0, _deburr["default"])(value.trim()).toLowerCase();
  var inputLength = inputValue.length;
  var count = 0;
  return inputLength === 0 ? suggestions : suggestions.filter(function (suggestion) {
    var keep = count < 5 && suggestion.label.slice(0, inputLength).toLowerCase() === inputValue;

    if (keep) {
      count += 1;
    }

    return keep;
  });
}

function getSuggestionValue(suggestion) {
  return suggestion.label;
}

function AutoComplete(props) {
  var library = props.library,
      attributes = props.attributes,
      control = props.control,
      onChange = props.onChange;
  var label = attributes.label,
      id = attributes.id,
      custominputprops = attributes.custominputprops;
  var useStyles = library.makeStyles(function (theme) {
    return {
      root: {
        flexGrow: 1
      },
      container: {
        position: 'relative'
      },
      suggestionsContainerOpen: {
        position: 'absolute',
        zIndex: 3,
        marginTop: theme.spacing(0.5),
        left: 0,
        right: 0,
        maxHeight: 180,
        overflowY: 'auto'
      },
      suggestion: {
        display: 'block'
      },
      suggestionsList: {
        margin: 0,
        padding: 0,
        listStyleType: 'none'
      },
      divider: {
        height: theme.spacing(2)
      }
    };
  });

  function renderInputComponent(inputProps) {
    var classes = inputProps.classes,
        _inputProps$inputRef = inputProps.inputRef,
        _inputRef = _inputProps$inputRef === void 0 ? function () {} : _inputProps$inputRef,
        ref = inputProps.ref,
        other = _objectWithoutProperties(inputProps, ["classes", "inputRef", "ref"]);

    var TEXTFIELD = library.TextField;
    return /*#__PURE__*/_react["default"].createElement(TEXTFIELD, _extends({
      fullWidth: true,
      InputProps: _objectSpread({
        inputRef: function inputRef(node) {
          ref(node);

          _inputRef(node);
        },
        classes: {
          input: classes.input
        }
      }, getInputProps())
    }, other));
  }

  function getInputProps() {
    if (custominputprops) {
      if (custominputprops.InputAdornment) {
        var INPUTADORMENT = library.InputAdornment;
        var ICON = library.Icon;
        return {
          startAdornment: /*#__PURE__*/_react["default"].createElement(INPUTADORMENT, custominputprops.InputAdornment, custominputprops.InputAdornment.icon ? /*#__PURE__*/_react["default"].createElement(ICON, null, custominputprops.InputAdornment.icon) : custominputprops.InputAdornment.text || '')
        };
      }
    }

    return {};
  }

  function renderSuggestion(suggestion, _ref) {
    var query = _ref.query,
        isHighlighted = _ref.isHighlighted;
    var matches = (0, _match["default"])(suggestion.label, query);
    var parts = (0, _parse["default"])(suggestion.label, matches);
    var MENUITEM = library.MenuItem;
    return /*#__PURE__*/_react["default"].createElement(MENUITEM, {
      selected: isHighlighted,
      component: "div"
    }, /*#__PURE__*/_react["default"].createElement("div", null, parts.map(function (part, index) {
      return part.highlight ? /*#__PURE__*/_react["default"].createElement("span", {
        key: String(index),
        style: {
          fontWeight: 500
        }
      }, part.text) : /*#__PURE__*/_react["default"].createElement("strong", {
        key: String(index),
        style: {
          fontWeight: 300
        }
      }, part.text);
    })));
  }

  var classes = useStyles();

  var _React$useState = _react["default"].useState(_defineProperty({
    single: '',
    popper: ''
  }, id, attributes.value || '')),
      _React$useState2 = _slicedToArray(_React$useState, 2),
      state = _React$useState2[0],
      setState = _React$useState2[1];

  var _React$useState4 = _react["default"].useState([]),
      _React$useState5 = _slicedToArray(_React$useState4, 2),
      stateSuggestions = _React$useState5[0],
      setSuggestions = _React$useState5[1];

  var handleSuggestionsFetchRequested = function handleSuggestionsFetchRequested(_ref2) {
    var value = _ref2.value;
    setSuggestions(getSuggestions(value, control.suggestions));
  };

  var handleSuggestionsClearRequested = function handleSuggestionsClearRequested() {
    setSuggestions([]);
  };

  var handleChange = function handleChange(name) {
    return function (event, _ref3) {
      var newValue = _ref3.newValue;
      setState(_objectSpread(_objectSpread({}, state), {}, _defineProperty({}, name, newValue)));
      onChange(control, newValue);
    };
  };

  var handleOnSuggestionSelected = function handleOnSuggestionSelected(name, newValue) {
    setState(_objectSpread(_objectSpread({}, state), {}, _defineProperty({}, name, newValue)));
    onChange(control, newValue);
  };

  var autosuggestProps = {
    renderInputComponent: renderInputComponent,
    suggestions: stateSuggestions,
    onSuggestionsFetchRequested: handleSuggestionsFetchRequested,
    onSuggestionsClearRequested: handleSuggestionsClearRequested,
    getSuggestionValue: getSuggestionValue,
    renderSuggestion: renderSuggestion
  };
  var PAPER = library.Paper;
  return /*#__PURE__*/_react["default"].createElement("div", {
    className: classes.root,
    style: attributes.style
  }, /*#__PURE__*/_react["default"].createElement(_reactAutosuggest["default"], _extends({}, autosuggestProps, {
    inputProps: {
      id: id,
      classes: classes,
      label: label,
      value: state[id],
      onChange: handleChange(id),
      margin: 'normal',
      variant: 'outlined',
      autoComplete: 'nope'
    },
    theme: {
      container: classes.container,
      suggestionsContainerOpen: classes.suggestionsContainerOpen,
      suggestionsList: classes.suggestionsList,
      suggestion: classes.suggestion
    },
    shouldRenderSuggestions: function shouldRenderSuggestions() {
      return true;
    },
    renderSuggestionsContainer: function renderSuggestionsContainer(options) {
      return /*#__PURE__*/_react["default"].createElement(PAPER, _extends({}, options.containerProps, {
        square: true
      }), options.children);
    },
    onSuggestionSelected: function onSuggestionSelected(e, suggestionSelect) {
      handleOnSuggestionSelected(id, suggestionSelect.suggestionValue);
    }
  })));
}

AutoComplete.propTypes = process.env.NODE_ENV !== "production" ? {
  library: _propTypes["default"].object,
  component: _propTypes["default"].string.isRequired,
  attributes: _propTypes["default"].object,
  control: _propTypes["default"].object,
  rules: _propTypes["default"].object,
  onChange: _propTypes["default"].func
} : {};
AutoComplete.defaultProps = {
  library: null,
  attributes: null,
  control: null,
  rules: null,
  onChange: null
};
var _default = AutoComplete;
exports["default"] = _default;