'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _getClassName2 = require('babel-plugin-react-css-modules/dist/browser/getClassName');

var _getClassName3 = _interopRequireDefault(_getClassName2);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

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

var _propTypes2 = _interopRequireDefault(_propTypes);

var _classnames = require('classnames');

var _classnames2 = _interopRequireDefault(_classnames);

var _index = require('../Dropdown/index');

var _index2 = _interopRequireDefault(_index);

var _index3 = require('./SearchGroup/index');

var _index4 = _interopRequireDefault(_index3);

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

var _styleModuleImportMap = {
  './autocomplete.scss': {
    'input-group': 'flive_autocomplete_input-group',
    'no-match': 'flive_autocomplete_no-match',
    'item': 'flive_autocomplete_item',
    'selected': 'flive_autocomplete_selected',
    'results': 'flive_autocomplete_results'
  }
};

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 Content = _index2.default.Content,
    Item = _index2.default.Item;


var propTypes = {
  onSelection: _propTypes2.default.func,
  indexes: _propTypes2.default.array,
  noMatchLabel: _propTypes2.default.string,
  placeholder: _propTypes2.default.string,
  hideDropdown: _propTypes2.default.bool,
  className: _propTypes2.default.string,
  style: _propTypes2.default.object,
  ignoreCase: _propTypes2.default.bool,
  input: _propTypes2.default.object,
  onChange: _propTypes2.default.func,
  matches: _propTypes2.default.array,
  value: _propTypes2.default.string,
  handleChange: _propTypes2.default.func,
  label: _propTypes2.default.string,
  html: _propTypes2.default.bool
};

var defaultProps = {
  onSelection: function onSelection() {},
  indexes: [],
  noMatchLabel: undefined,
  placeholder: undefined,
  hideDropdown: false,
  className: '',
  style: null,
  ignoreCase: false,
  input: {},
  onChange: null,
  matches: null,
  value: null,
  handleChange: null,
  label: '',
  html: false
};

/**
 * Autocomplete input
 *
 */

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

  function Autocomplete() {
    var _ref;

    var _temp, _this, _ret;

    _classCallCheck(this, Autocomplete);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Autocomplete.__proto__ || Object.getPrototypeOf(Autocomplete)).call.apply(_ref, [this].concat(args))), _this), _this.state = {
      value: '',
      matchedIndexes: [],
      currentSelected: -1
    }, _this.setDropdownRef = function (node) {
      _this.dropdown = node;
    }, _this.handleChange = function (e) {
      _this.filterResults(e.target.value);
    }, _this.handleFocus = function () {
      var value = _this.state.value;


      if (_this.props.matches && (_this.props.matches.length > 0 || value.length >= 3)) {
        _this.dropdown.openPanel();
      }
    }, _this.filterResults = function (value) {
      var _this$props = _this.props,
          indexes = _this$props.indexes,
          noMatchLabel = _this$props.noMatchLabel,
          ignoreCase = _this$props.ignoreCase;

      var matchedIndexes = [];
      if (value.length >= 3) {
        matchedIndexes = ignoreCase ? indexes.filter(function (index) {
          return index.toLowerCase().indexOf(value.toLowerCase()) === 0;
        }) : indexes.filter(function (index) {
          return index.indexOf(value) === 0;
        });
        if (matchedIndexes.length) {
          _this.dropdown.openPanel();
        } else if (noMatchLabel) {
          _this.dropdown.openPanel();
        } else {
          _this.dropdown.closePanel();
        }
      } else {
        _this.dropdown.closePanel();
      }
      _this.props.onChange(matchedIndexes);
      _this.setState({ value: value, matchedIndexes: matchedIndexes, currentSelected: -1 });
    }, _this.handleSelection = function (value, index) {
      return function () {
        var onSelection = _this.props.onSelection;

        if (!_this.props.matches) _this.filterResults(value);
        _this.dropdown.closePanel();
        onSelection(value, index);
      };
    }, _this.handleSubmit = function (e) {
      var _this$state = _this.state,
          stateValue = _this$state.value,
          matchedIndexes = _this$state.matchedIndexes,
          currentSelected = _this$state.currentSelected;
      var _this$props2 = _this.props,
          matches = _this$props2.matches,
          propsValue = _this$props2.value;

      var realMatches = matches || matchedIndexes;
      var value = propsValue || stateValue;
      e.preventDefault();

      if (currentSelected > -1) {
        _this.handleSelection(realMatches[currentSelected], currentSelected)();
      } else {
        _this.handleSelection(value)();
      }
      _this.setState({ value: '' });
    }, _this.handleNavigation = function (e) {
      var matches = _this.props.matches;
      var _this$state2 = _this.state,
          matchedIndexes = _this$state2.matchedIndexes,
          currentSelected = _this$state2.currentSelected;

      var realMatches = matches || matchedIndexes;
      if (e.key === 'ArrowDown') {
        e.preventDefault();
        if (currentSelected < realMatches.length - 1) {
          _this.setState({ currentSelected: currentSelected + 1 });
        }
      } else if (e.key === 'ArrowUp') {
        e.preventDefault();
        if (currentSelected >= 0) {
          _this.setState({ currentSelected: currentSelected - 1 });
        }
      }
    }, _temp), _possibleConstructorReturn(_this, _ret);
  }

  _createClass(Autocomplete, [{
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps) {
      if (nextProps.matches && nextProps.matches.length > 0) {
        this.dropdown.openPanel();
      } else if (nextProps.matches && nextProps.matches.length !== this.props.matches.length && nextProps.matches.length === 0) {
        this.dropdown.closePanel();
      }
    }
  }, {
    key: 'render',
    value: function render() {
      var _this2 = this;

      var _props = this.props,
          noMatchLabel = _props.noMatchLabel,
          placeholder = _props.placeholder,
          hideDropdown = _props.hideDropdown,
          className = _props.className,
          style = _props.style,
          input = _props.input,
          matches = _props.matches,
          handleChange = _props.handleChange,
          propsValue = _props.value,
          label = _props.label,
          html = _props.html;
      var _state = this.state,
          stateValue = _state.value,
          matchedIndexes = _state.matchedIndexes,
          currentSelected = _state.currentSelected;

      var realMatches = matches || matchedIndexes;
      var value = propsValue || stateValue;
      return _react2.default.createElement(
        _index2.default,
        {
          variant: 'full-width',

          ref: this.setDropdownRef,
          className: (className ? className + ' ' : '') + 'flive_autocomplete_results',
          style: style
        },
        function (_ref2) {
          var openPanel = _ref2.openPanel,
              closePanel = _ref2.closePanel,
              togglePanel = _ref2.togglePanel,
              variant = _ref2.variant,
              isActive = _ref2.isActive,
              reverse = _ref2.reverse;

          var resultRender = [_react2.default.createElement(_index4.default, {
            value: value,
            key: 'trigger',
            placeholder: placeholder,
            onFocus: _this2.handleFocus,
            onSubmit: _this2.handleSubmit,
            onChange: matches ? handleChange : _this2.handleChange,
            onKeyDown: _this2.handleNavigation,
            input: input,
            onClick: togglePanel,
            openPanel: openPanel,
            closePanel: closePanel,
            label: label
          })];
          if (!hideDropdown) {
            resultRender.push(_react2.default.createElement(
              Content,
              {
                key: 'content',
                variant: variant,
                active: isActive,
                reverse: reverse
              },
              realMatches.length === 0 ? _react2.default.createElement(
                'div',
                { className: 'flive_autocomplete_no-match' },
                noMatchLabel
              ) : realMatches.map(function (v, k) {
                return (typeof v === 'undefined' ? 'undefined' : _typeof(v)) === 'object' ? _react2.default.createElement(
                  Item,
                  {
                    onClick: _this2.handleSelection(v, k),
                    key: 'autocomplete' + v.value,
                    className: (0, _getClassName3.default)((0, _classnames2.default)('item', { selected: currentSelected === k }), _styleModuleImportMap)
                  },
                  html ? _react2.default.createElement('div', { dangerouslySetInnerHTML: { __html: v.value } }) : v.value
                ) : _react2.default.createElement(
                  Item,
                  {
                    onClick: _this2.handleSelection(v, k),
                    key: 'autocomplete' + v,
                    className: (0, _getClassName3.default)((0, _classnames2.default)('item', { selected: currentSelected === k }), _styleModuleImportMap)
                  },
                  html ? _react2.default.createElement('div', { dangerouslySetInnerHTML: { __html: v } }) : v
                );
              })
            ));
          }
          return resultRender;
        }
      );
    }
  }]);

  return Autocomplete;
}(_react.Component);

Autocomplete.propTypes = propTypes;
Autocomplete.defaultProps = defaultProps;

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