'use strict';

exports.__esModule = true;

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _reactAutosuggest = require('react-autosuggest');

var _reactAutosuggest2 = _interopRequireDefault(_reactAutosuggest);

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

var _parse2 = _interopRequireDefault(_parse);

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

var _match2 = _interopRequireDefault(_match);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _classnames = require('classnames');

var _classnames2 = _interopRequireDefault(_classnames);

require('./style.css');

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

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; }

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 = (0, _match2.default)(suggestionText, query);
      var parts = (0, _parse2.default)(suggestionText, matches);
      return _react2.default.createElement(
        'span',
        { className: 'suggestion-content' },
        _react2.default.createElement(
          'span',
          { className: 'name' },
          parts.map(function (part, index) {
            var className = part.highlight ? 'highlight' : null;
            var key = 'suggestion_' + index;
            return _react2.default.createElement(
              'span',
              { className: className, key: key },
              part.text
            );
          })
        )
      );
    };
    var inputTextTypeAheadClasses = (0, _classnames2.default)({
      'ma__input-typeahead': true,
      'ma__input-typeahead--boxed': boxed,
      'ma__input-typeahead--disabled': disabled
    });
    return _react2.default.createElement(
      _react2.default.Fragment,
      null,
      label && _react2.default.createElement(
        'label',
        { htmlFor: id, className: 'ma__label' },
        label
      ),
      _react2.default.createElement(
        'div',
        { className: inputTextTypeAheadClasses },
        _react2.default.createElement(_reactAutosuggest2.default, {
          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;
}(_react.Component);

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

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

exports.default = InputTextTypeAhead;
module.exports = exports['default'];