'use strict';

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

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 _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 _react2 = _interopRequireDefault(_react);

var _classnames = require('classnames');

var _classnames2 = _interopRequireDefault(_classnames);

var _DropdownMenuInput = require('./DropdownMenuInput');

var _DropdownMenuInput2 = _interopRequireDefault(_DropdownMenuInput);

var _changeable = require('../enhancers/changeable');

var _changeable2 = _interopRequireDefault(_changeable);

var _optionHelpers = require('../helpers/optionHelpers');

var _pathHelpers = require('../helpers/pathHelpers');

var _FilteringDropdownMenuInput = require('../../styles/cspace-input/FilteringDropdownMenuInput.css');

var _FilteringDropdownMenuInput2 = _interopRequireDefault(_FilteringDropdownMenuInput);

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

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { 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) : subClass.__proto__ = superClass; }

var DropdownMenuInput = (0, _changeable2.default)(_DropdownMenuInput2.default);

var propTypes = _extends({}, DropdownMenuInput.propTypes, {
  blankable: _react.PropTypes.bool,
  formatStatusMessage: _react.PropTypes.func,
  filter: _react.PropTypes.func,
  onClose: _react.PropTypes.func,
  onCommit: _react.PropTypes.func
});

var defaultProps = {
  blankable: true,
  formatStatusMessage: function formatStatusMessage(count) {
    var matches = count === 1 ? 'match' : 'matches';
    var num = count === 0 ? 'No' : count;

    return num + ' ' + matches + ' found';
  }
};

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

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

    var _this = _possibleConstructorReturn(this, (FilteringDropdownMenuInput.__proto__ || Object.getPrototypeOf(FilteringDropdownMenuInput)).call(this, props));

    _this.handleDropdownInputChange = _this.handleDropdownInputChange.bind(_this);
    _this.handleDropdownInputClose = _this.handleDropdownInputClose.bind(_this);
    _this.handleDropdownInputCommit = _this.handleDropdownInputCommit.bind(_this);
    _this.handleDropdownInputKeyDown = _this.handleDropdownInputKeyDown.bind(_this);
    _this.handleDropdownInputOpen = _this.handleDropdownInputOpen.bind(_this);

    _this.state = {
      isFiltering: false,
      open: false,
      value: _this.props.value
    };
    return _this;
  }

  _createClass(FilteringDropdownMenuInput, [{
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps) {
      this.setState({
        value: nextProps.value
      });
    }
  }, {
    key: 'close',
    value: function close() {
      this.setState({
        open: false
      });
    }
  }, {
    key: 'commit',
    value: function commit(value) {
      var onCommit = this.props.onCommit;


      if (onCommit) {
        onCommit((0, _pathHelpers.getPath)(this.props), value);
      }
    }
  }, {
    key: 'filter',
    value: function filter(filterByValue) {
      var filter = this.props.filter;


      if (filter) {
        filter(filterByValue);
      }
    }
  }, {
    key: 'handleDropdownInputChange',
    value: function handleDropdownInputChange(value) {
      this.setState({
        isFiltering: true,
        open: true,
        valueLabel: value
      });

      this.filter(value);
    }
  }, {
    key: 'handleDropdownInputCommit',
    value: function handleDropdownInputCommit(path, value) {
      this.setState({
        value: value,
        isFiltering: false,
        open: false
      });

      this.filter();
      this.commit(value);
    }
  }, {
    key: 'handleDropdownInputKeyDown',
    value: function handleDropdownInputKeyDown(event) {
      var isFiltering = this.state.isFiltering;


      if (isFiltering && event.key === 'Enter') {
        event.preventDefault();

        var valueLabel = this.state.valueLabel;
        var _props = this.props,
            blankable = _props.blankable,
            options = _props.options;

        // If there is only one option, select it. Otherwise, if the current content of the
        // input matches an option exactly, select it.

        var matchingOption = options.length === 1 ? options[0] : (0, _optionHelpers.getOptionForLabel)(options, valueLabel);

        if (!matchingOption && blankable && valueLabel === '') {
          // If blankable, and the current content of the input is empty, allow it to be
          // committed even if there is no empty option.

          matchingOption = {
            value: '',
            valueLabel: ''
          };
        }

        if (matchingOption) {
          this.setState({
            open: false,
            value: matchingOption.value,
            valueLabel: matchingOption.label
          });

          this.commit(matchingOption.value);
        }
      }
    }
  }, {
    key: 'handleDropdownInputClose',
    value: function handleDropdownInputClose() {
      this.setState({
        isFiltering: false,
        open: false
      });

      var onClose = this.props.onClose;


      if (onClose) {
        onClose();
      }
    }
  }, {
    key: 'handleDropdownInputOpen',
    value: function handleDropdownInputOpen() {
      this.setState({
        isFiltering: false,
        open: true
      });

      this.filter();
    }
  }, {
    key: 'renderMenuHeader',
    value: function renderMenuHeader() {
      var isFiltering = this.state.isFiltering;
      var _props2 = this.props,
          formatStatusMessage = _props2.formatStatusMessage,
          options = _props2.options;


      if (isFiltering) {
        return _react2.default.createElement(
          'span',
          null,
          formatStatusMessage(options ? options.length : 0)
        );
      }

      return null;
    }
  }, {
    key: 'render',
    value: function render() {
      var _state = this.state,
          isFiltering = _state.isFiltering,
          open = _state.open,
          value = _state.value,
          valueLabel = _state.valueLabel;

      var _props3 = this.props,
          className = _props3.className,
          formatStatusMessage = _props3.formatStatusMessage,
          remainingProps = _objectWithoutProperties(_props3, ['className', 'formatStatusMessage']);

      var valueProp = isFiltering ? { valueLabel: valueLabel } : { value: value };

      var classes = (0, _classnames2.default)(className, _defineProperty({}, _FilteringDropdownMenuInput2.default.filtering, isFiltering));

      return _react2.default.createElement(DropdownMenuInput, _extends({}, remainingProps, valueProp, {
        className: classes,
        menuHeader: this.renderMenuHeader(),
        open: open,
        onChange: this.handleDropdownInputChange,
        onClose: this.handleDropdownInputClose,
        onCommit: this.handleDropdownInputCommit,
        onKeyDown: this.handleDropdownInputKeyDown,
        onOpen: this.handleDropdownInputOpen
      }));
    }
  }]);

  return FilteringDropdownMenuInput;
}(_react.Component);

exports.default = FilteringDropdownMenuInput;


FilteringDropdownMenuInput.propTypes = propTypes;
FilteringDropdownMenuInput.defaultProps = defaultProps;