'use strict';

exports.__esModule = true;

var _kebabCase2 = require('lodash/kebabCase');

var _kebabCase3 = _interopRequireDefault(_kebabCase2);

var _trim2 = require('lodash/trim');

var _trim3 = _interopRequireDefault(_trim2);

var _eq2 = require('lodash/eq');

var _eq3 = _interopRequireDefault(_eq2);

var _isUndefined2 = require('lodash/isUndefined');

var _isUndefined3 = _interopRequireDefault(_isUndefined2);

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

var _react = require('react');

var React = _interopRequireWildcard(_react);

var _classnames = require('classnames');

var _classnames2 = _interopRequireDefault(_classnames);

var _setStatic = require('recompose/setStatic');

var _setStatic2 = _interopRequireDefault(_setStatic);

var _OverlayTrigger = require('rsuite-utils/lib/Overlay/OverlayTrigger');

var _OverlayTrigger2 = _interopRequireDefault(_OverlayTrigger);

var _Picker = require('rsuite-utils/lib/Picker');

var _Input = require('./Input');

var _Input2 = _interopRequireDefault(_Input);

var _AutoCompleteItem = require('./AutoCompleteItem');

var _AutoCompleteItem2 = _interopRequireDefault(_AutoCompleteItem);

var _utils = require('./utils');

var _prefix = require('./utils/prefix');

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

var _propTypes2 = _interopRequireDefault(_propTypes);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

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

function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

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) : _defaults(subClass, superClass); }

var AutoComplete = function (_React$Component) {
  _inherits(AutoComplete, _React$Component);

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

    var _this = _possibleConstructorReturn(this, _React$Component.call(this, props));

    _this.getFocusableMenuItems = function () {
      var data = _this.props.data;

      if (!data) {
        return [];
      }
      return data.filter(_this.shouldDisplay);
    };

    _this.trigger = null;
    _this.menuContainer = null;

    _this.shouldDisplay = function (label) {
      var value = _this.state.value;

      if (!(0, _trim3.default)(value)) {
        return false;
      }
      var keyword = value.toLocaleLowerCase();
      return label.toLocaleLowerCase().indexOf(keyword) >= 0;
    };

    _this.handleChange = function (value, event) {
      var onChange = _this.props.onChange;

      _this.setState({
        focus: true,
        focusItemValue: undefined,
        value: value
      });
      if (_this.state.value !== value) {
        onChange && onChange(value, event);
      }
    };

    _this.handleInputFocus = function (event) {
      var onFocus = _this.props.onFocus;

      _this.open();
      onFocus && onFocus(event);
    };

    _this.handleInputBlur = function (event) {
      var onBlur = _this.props.onBlur;

      setTimeout(_this.close, 300);
      onBlur && onBlur(event);
    };

    _this.close = function () {
      _this.setState({ focus: false });
    };

    _this.open = function () {
      _this.setState({ focus: true });
    };

    _this.handleKeyDown = function (event) {
      if (!_this.menuContainer) {
        return;
      }

      switch (event.keyCode) {
        // down
        case 40:
          _this.focusNextMenuItem();
          event.preventDefault();
          break;
        // up
        case 38:
          _this.focusPrevMenuItem();
          event.preventDefault();
          break;
        // enter
        case 13:
          _this.selectFocusMenuItem(event);
          event.preventDefault();
          break;
        // esc | tab
        case 27:
        case 9:
          _this.close();
          event.preventDefault();
          break;
        default:
      }
    };

    _this.handleSelect = function (value, event) {
      var _this$props = _this.props,
          onChange = _this$props.onChange,
          onSelect = _this$props.onSelect;

      _this.setState({
        value: value,
        focusItemValue: value
      });

      onSelect && onSelect(value, event);

      if (_this.state.value !== value) {
        onChange && onChange(value, event);
      }
      _this.close();
    };

    _this.addPrefix = function (name) {
      return (0, _utils.prefix)(_this.props.classPrefix)(name);
    };

    _this.menuContainerRef = function (ref) {
      _this.menuContainer = ref;
    };

    _this.triggerRef = function (ref) {
      _this.trigger = ref;
    };

    var nextValue = props.defaultValue;

    _this.state = {
      value: nextValue || '',
      focus: false,
      focusItemValue: nextValue
    };
    return _this;
  }

  AutoComplete.prototype.getValue = function getValue() {
    var value = this.props.value;

    return (0, _isUndefined3.default)(value) ? this.state.value : value;
  };

  AutoComplete.prototype.findNode = function findNode(focus) {
    var items = this.getFocusableMenuItems();
    var focusItemValue = this.state.focusItemValue;


    for (var i = 0; i < items.length; i += 1) {
      if ((0, _eq3.default)(focusItemValue, items[i])) {
        focus(items, i);
        return;
      }
    }

    focus(items, -1);
  };

  AutoComplete.prototype.focusNextMenuItem = function focusNextMenuItem() {
    var _this2 = this;

    this.findNode(function (items, index) {
      var focusItemValue = items[index + 1];
      if (!(0, _isUndefined3.default)(focusItemValue)) {
        _this2.setState({ focusItemValue: focusItemValue });
      }
    });
  };

  AutoComplete.prototype.focusPrevMenuItem = function focusPrevMenuItem() {
    var _this3 = this;

    this.findNode(function (items, index) {
      var focusItemValue = items[index - 1];
      if (!(0, _isUndefined3.default)(focusItemValue)) {
        _this3.setState({ focusItemValue: focusItemValue });
      }
    });
  };

  AutoComplete.prototype.selectFocusMenuItem = function selectFocusMenuItem(event) {
    var _this4 = this;

    var onChange = this.props.onChange;
    var focusItemValue = this.state.focusItemValue;


    if (!focusItemValue) {
      return;
    }

    this.setState({
      value: focusItemValue,
      focusItemValue: focusItemValue
    }, function () {
      onChange && onChange(focusItemValue, event);
      _this4.close();
    });
  };

  AutoComplete.prototype.renderDropdownMenu = function renderDropdownMenu() {
    var _this5 = this;

    var _props = this.props,
        placement = _props.placement,
        renderItem = _props.renderItem,
        data = _props.data;
    var focusItemValue = this.state.focusItemValue;

    var classes = (0, _classnames2.default)(this.addPrefix('menu'), _prefix.globalKey + 'placement-' + (0, _kebabCase3.default)(placement));
    var items = data.filter(this.shouldDisplay);

    return React.createElement(
      _Picker.MenuWrapper,
      { className: classes, onKeyDown: this.handleKeyDown },
      React.createElement(
        'div',
        { ref: this.menuContainerRef },
        React.createElement(
          'ul',
          { role: 'menu' },
          items.map(function (item) {
            return React.createElement(
              _AutoCompleteItem2.default,
              {
                key: item,
                focus: focusItemValue === item,
                value: item,
                onSelect: _this5.handleSelect,
                renderItem: renderItem
              },
              item
            );
          })
        )
      )
    );
  };

  AutoComplete.prototype.render = function render() {
    var _classNames;

    var _props2 = this.props,
        disabled = _props2.disabled,
        className = _props2.className,
        classPrefix = _props2.classPrefix,
        defaultValue = _props2.defaultValue,
        placement = _props2.placement,
        data = _props2.data,
        open = _props2.open,
        style = _props2.style,
        rest = _objectWithoutProperties(_props2, ['disabled', 'className', 'classPrefix', 'defaultValue', 'placement', 'data', 'open', 'style']);

    var value = this.getValue();
    var unhandled = (0, _utils.getUnhandledProps)(AutoComplete, rest);
    var classes = (0, _classnames2.default)(classPrefix, className, (_classNames = {}, _classNames[this.addPrefix('disabled')] = disabled, _classNames));

    var hasItems = data.filter(this.shouldDisplay).length > 0;

    return React.createElement(
      'div',
      { className: classes, style: style },
      React.createElement(
        _OverlayTrigger2.default,
        {
          ref: this.triggerRef,
          disabled: disabled,
          trigger: ['click', 'focus'],
          placement: placement,
          open: open || this.state.focus && hasItems,
          speaker: this.renderDropdownMenu()
        },
        React.createElement(_Input2.default, _extends({}, unhandled, {
          disabled: disabled,
          value: value,
          onBlur: this.handleInputBlur,
          onFocus: this.handleInputFocus,
          onChange: this.handleChange,
          onKeyDown: this.handleKeyDown
        }))
      )
    );
  };

  return AutoComplete;
}(React.Component);

AutoComplete.defaultProps = {
  data: [],
  placement: 'bottomLeft'
};
AutoComplete.handledProps = ['className', 'classPrefix', 'data', 'defaultValue', 'disabled', 'onBlur', 'onChange', 'onFocus', 'onSelect', 'open', 'placement', 'renderItem', 'style', 'value'];
AutoComplete.propTypes = {
  data: _propTypes2.default.arrayOf(_propTypes2.default.string).isRequired,
  disabled: _propTypes2.default.bool,
  onSelect: _propTypes2.default.func,
  onChange: _propTypes2.default.func,
  classPrefix: _propTypes2.default.string,
  value: _propTypes2.default.string,
  defaultValue: _propTypes2.default.string,
  className: _propTypes2.default.string,
  placement: _propTypes2.default.oneOf(['bottomLeft', 'bottomRight', 'topLeft', 'topRight', 'leftTop', 'rightTop', 'leftBottom', 'rightBottom']),
  onFocus: _propTypes2.default.func,
  onBlur: _propTypes2.default.func,
  renderItem: _propTypes2.default.func,
  style: _propTypes2.default.object,
  open: _propTypes2.default.bool
};


var EnhancedAutoComplete = (0, _utils.defaultProps)({
  classPrefix: 'auto-complete'
})(AutoComplete);

(0, _setStatic2.default)('Item', _AutoCompleteItem2.default)(AutoComplete);

exports.default = EnhancedAutoComplete;