function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

import React, { Component } from 'react';
import Autosuggest from 'react-autosuggest';
import parse from 'autosuggest-highlight/parse';
import match from 'autosuggest-highlight/match';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import './style.css';

var InputTextTypeAhead = function (_Component) {
  _inherits(InputTextTypeAhead, _Component);

  function InputTextTypeAhead(props) {
    _classCallCheck(this, InputTextTypeAhead);

    var _this = _possibleConstructorReturn(this, _Component.call(this, props));

    _this.state = {
      value: props.clearInputTextTypeAheadSelected || !props.selected ? '' : props.selected,
      suggestions: []
    };
    _this.selectTag = '';
    _this.onChange = _this.onChange.bind(_this);
    _this.onBlur = _this.onBlur.bind(_this);
    _this.onSuggestionsFetchRequested = _this.onSuggestionsFetchRequested.bind(_this);
    _this.onSuggestionsClearRequested = _this.onSuggestionsClearRequested.bind(_this);
    _this.onSuggestionSelected = _this.onSuggestionSelected.bind(_this);
    _this.getSuggestions = _this.getSuggestions.bind(_this);
    _this.onKeyDown = _this.onKeyDown.bind(_this);
    if (process.env.NODE_ENV === 'development') {
      /* eslint-disable-next-line no-console */
      console.warn('This component is deprecated and will be archived in v10. Use InputTextFuzzy instead.');
    }
    return _this;
  }

  InputTextTypeAhead.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
    this.setState({ value: nextProps.selected });
    this.selectTag.selectedIndex = nextProps.options.findIndex(function (option) {
      return option.text === nextProps.selected;
    });
  };

  InputTextTypeAhead.prototype.onKeyDown = function onKeyDown(event) {
    if (typeof this.props.onKeyDown === 'function') {
      this.props.onKeyDown(event);
    }
  };

  InputTextTypeAhead.prototype.onChange = function onChange(event, _ref) {
    var newValue = _ref.newValue;

    this.setState({
      value: newValue
    });
    if (newValue.length === 0 && typeof this.props.onChange === 'function') {
      // Change the filter back to "" if the user clears the typeahead input.
      var suggestion = { text: '', value: '' };
      this.props.onChange(event, { suggestion: suggestion });
    }
  };

  InputTextTypeAhead.prototype.onBlur = function onBlur(event) {
    if (typeof this.props.onBlur === 'function') {
      this.props.onBlur(event);
    }
  };

  InputTextTypeAhead.prototype.onSuggestionsFetchRequested = function onSuggestionsFetchRequested(_ref2) {
    var value = _ref2.value;

    this.setState({
      suggestions: this.getSuggestions(value)
    });
  };

  InputTextTypeAhead.prototype.onSuggestionsClearRequested = function onSuggestionsClearRequested() {
    this.setState({
      suggestions: []
    });
  };

  InputTextTypeAhead.prototype.onSuggestionSelected = function onSuggestionSelected(event, _ref3) {
    var suggestion = _ref3.suggestion;

    // invokes custom function if passed in the component
    if (typeof this.props.onChange === 'function') {
      this.props.onChange(event, { suggestion: suggestion });
    }
  };

  InputTextTypeAhead.prototype.getSuggestions = function getSuggestions(value) {
    var escapeRegexCharacters = function escapeRegexCharacters(str) {
      return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    };
    var escapedValue = escapeRegexCharacters(value.trim());
    var regex = new RegExp('' + escapedValue, 'i');
    var options = this.props.options;

    if (escapedValue === '') {
      return options;
    }
    return options.filter(function (item) {
      return regex.test(item.text);
    });
  };

  InputTextTypeAhead.prototype.render = function render() {
    var _this2 = this;

    var suggestions = this.state.suggestions;
    var _props = this.props,
        boxed = _props.boxed,
        id = _props.id,
        label = _props.label,
        placeholder = _props.placeholder,
        autoFocusInput = _props.autoFocusInput,
        disabled = _props.disabled;

    var value = JSON.parse(JSON.stringify(this.state.value));
    var inputProps = {
      value: value,
      onKeyDown: this.onKeyDown,
      onChange: this.onChange,
      onBlur: this.onBlur,
      type: 'search',
      autoFocus: autoFocusInput,
      placeholder: placeholder,
      disabled: disabled
    };
    var shouldRenderSuggestions = function shouldRenderSuggestions(x) {
      return x.trim().length >= 0;
    };
    var getSuggestionValue = function getSuggestionValue(suggestion) {
      return suggestion.text;
    };
    var renderSuggestion = function renderSuggestion(suggestion, _ref4) {
      var query = _ref4.query;

      var suggestionText = '' + suggestion.text;
      var matches = match(suggestionText, query);
      var parts = parse(suggestionText, matches);
      return React.createElement(
        'span',
        { className: 'suggestion-content' },
        React.createElement(
          'span',
          { className: 'name' },
          parts.map(function (part, index) {
            var className = part.highlight ? 'highlight' : null;
            var key = 'suggestion_' + index;
            return React.createElement(
              'span',
              { className: className, key: key },
              part.text
            );
          })
        )
      );
    };
    var inputTextTypeAheadClasses = classNames({
      'ma__input-typeahead': true,
      'ma__input-typeahead--boxed': boxed,
      'ma__input-typeahead--disabled': disabled
    });
    return React.createElement(
      React.Fragment,
      null,
      label && React.createElement(
        'label',
        { htmlFor: id, className: 'ma__label' },
        label
      ),
      React.createElement(
        'div',
        { className: inputTextTypeAheadClasses },
        React.createElement(Autosuggest, {
          suggestions: suggestions,
          onSuggestionsFetchRequested: this.onSuggestionsFetchRequested,
          onSuggestionSelected: this.onSuggestionSelected,
          getSuggestionValue: getSuggestionValue,
          renderSuggestion: renderSuggestion,
          onSuggestionsClearRequested: this.onSuggestionsClearRequested,
          inputProps: inputProps,
          shouldRenderSuggestions: shouldRenderSuggestions,
          id: id,
          ref: function ref(select) {
            _this2.selectTag = select;
          }
        })
      )
    );
  };

  return InputTextTypeAhead;
}(Component);

InputTextTypeAhead.propTypes = process.env.NODE_ENV !== "production" ? {
  /** Style the input with a box outline */
  boxed: PropTypes.bool,
  /** The label text above the input text box */
  label: PropTypes.string,
  /** The placeholder text to appear in the input text box */
  placeholder: PropTypes.string.isRequired,
  /** The id of the typeahead element */
  id: PropTypes.string.isRequired,
  /** An array of options for the typeahead */
  options: PropTypes.arrayOf(PropTypes.shape({
    value: PropTypes.string.isRequired,
    text: PropTypes.string.isRequired
  })),
  /** Custom keydown callback */
  onKeyDown: PropTypes.func,
  /** Custom change function */
  onChange: PropTypes.func,
  /** Custom blur handler function */
  onBlur: PropTypes.func,
  /** The default value for the select box */
  selected: PropTypes.string,
  /** Focus on typeahead input */
  autoFocusInput: PropTypes.bool,
  clearInputTextTypeAheadSelected: PropTypes.bool,
  disabled: PropTypes.bool
} : {};

InputTextTypeAhead.defaultProps = {
  autoFocusInput: false,
  clearInputTextTypeAheadSelected: false,
  disabled: false
};

export default InputTextTypeAhead;