'use strict';

exports.__esModule = true;

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

var _kebabCase3 = _interopRequireDefault(_kebabCase2);

var _get2 = require('lodash/get');

var _get3 = _interopRequireDefault(_get2);

var _isEqual2 = require('lodash/isEqual');

var _isEqual3 = _interopRequireDefault(_isEqual2);

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

var _trim3 = _interopRequireDefault(_trim2);

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

var _eq3 = _interopRequireDefault(_eq2);

var _isString2 = require('lodash/isString');

var _isString3 = _interopRequireDefault(_isString2);

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 _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 _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));

    _initialiseProps.call(_this);

    var defaultValue = props.defaultValue;


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

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

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

  AutoComplete.prototype.getData = function getData(props) {
    var _ref = props || this.props,
        _ref$data = _ref.data,
        data = _ref$data === undefined ? [] : _ref$data;

    return data.map(function (item) {
      if ((0, _isString3.default)(item)) {
        return {
          value: item,
          label: item
        };
      }

      if ((typeof item === 'undefined' ? 'undefined' : _typeof(item)) === 'object') {
        return item;
      }
    });
  };

  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].value)) {
        focus(items, i);
        return;
      }
    }

    focus(items, -1);
  };

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

    var onMenuFocus = this.props.onMenuFocus;

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

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

    var onMenuFocus = this.props.onMenuFocus;

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

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

    var _state = this.state,
        focusItemValue = _state.focusItemValue,
        prevValue = _state.value;

    if (!focusItemValue) {
      return;
    }
    var nextState = {
      value: focusItemValue,
      focusItemValue: focusItemValue
    };

    var data = this.getData();
    var focusItem = data.find(function (item) {
      return (0, _isEqual3.default)((0, _get3.default)(item, 'value'), focusItemValue);
    });

    this.setState(nextState, function () {
      _this4.handleSelect(focusItem, event);
      if (!(0, _isEqual3.default)(prevValue, focusItemValue)) {
        _this4.handleChangeValue(focusItemValue, event);
      }
    });

    this.close();
  };

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

    var _props = this.props,
        placement = _props.placement,
        renderItem = _props.renderItem,
        menuClassName = _props.menuClassName;

    var data = this.getData();
    var focusItemValue = this.state.focusItemValue;

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

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

  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,
        open = _props2.open,
        style = _props2.style,
        rest = _objectWithoutProperties(_props2, ['disabled', 'className', 'classPrefix', 'defaultValue', 'placement', 'open', 'style']);

    var data = this.getData();
    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', 'menuClassName', 'onBlur', 'onChange', 'onClose', 'onFocus', 'onKeyDown', 'onMenuFocus', 'onOpen', 'onSelect', 'open', 'placement', 'renderItem', 'style', 'value'];
AutoComplete.propTypes = {
  data: _propTypes2.default.arrayOf(_propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.shape({
    label: function label(props, propName, componentName) {
      if (!Object.prototype.hasOwnProperty.call(props, propName)) {
        throw new Error('Prop `' + propName + '` has type \'any\' or \'mixed\', but was not provided to `' + componentName + '`. Pass undefined or any other value.');
      }
    },
    value: function value(props, propName, componentName) {
      if (!Object.prototype.hasOwnProperty.call(props, propName)) {
        throw new Error('Prop `' + propName + '` has type \'any\' or \'mixed\', but was not provided to `' + componentName + '`. Pass undefined or any other value.');
      }
    }
  })])).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,
  menuClassName: _propTypes2.default.string,
  placement: _propTypes2.default.oneOf(['bottomLeft', 'bottomRight', 'topLeft', 'topRight', 'leftTop', 'rightTop', 'leftBottom', 'rightBottom']),
  onFocus: _propTypes2.default.func,
  onMenuFocus: _propTypes2.default.func,
  onBlur: _propTypes2.default.func,
  onKeyDown: _propTypes2.default.func,
  onOpen: _propTypes2.default.func,
  onClose: _propTypes2.default.func,
  renderItem: _propTypes2.default.func,
  style: _propTypes2.default.object,
  open: _propTypes2.default.bool
};

var _initialiseProps = function _initialiseProps() {
  var _this6 = this;

  this.getFocusableMenuItems = function () {
    var data = _this6.getData();
    if (!data) {
      return [];
    }
    return data.filter(_this6.shouldDisplay);
  };

  this.trigger = null;
  this.menuContainer = null;

  this.shouldDisplay = function (item) {
    var value = _this6.state.value;

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

  this.handleChange = function (value, event) {
    var nextState = {
      focus: true,
      focusItemValue: undefined,
      value: value
    };
    _this6.setState(nextState, function () {
      _this6.handleChangeValue(value, event);
    });
  };

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

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

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

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

  this.close = function () {
    _this6.setState({ focus: false }, _this6.props.onClose);
  };

  this.open = function () {
    _this6.setState({ focus: true }, _this6.props.onOpen);
  };

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

    var onKeyDown = _this6.props.onKeyDown;


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

  this.handleChangeValue = function (value, event) {
    var onChange = _this6.props.onChange;

    onChange && onChange(value, event);
  };

  this.handleSelect = function (item, event) {
    var onSelect = _this6.props.onSelect;

    onSelect && onSelect(item, event);
  };

  this.handleItemSelect = function (item, event) {
    var onSelect = _this6.props.onSelect;

    var value = item.value;
    var prevValue = _this6.state.value;
    var nextState = {
      value: value,
      focusItemValue: value
    };
    _this6.setState(nextState, function () {
      _this6.handleSelect(item, event);
      if (!(0, _isEqual3.default)(prevValue, value)) {
        _this6.handleChangeValue(value, event);
      }
    });
    _this6.close();
  };

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

  this.menuContainerRef = function (ref) {
    _this6.menuContainer = ref;
  };

  this.triggerRef = function (ref) {
    _this6.trigger = ref;
  };
};

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

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

exports.default = EnhancedAutoComplete;