'use strict';

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

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 _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 _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _OptClass = require('../internal/OptClass');

var _OptClass2 = _interopRequireDefault(_OptClass);

var _TagList = require('../internal/TagList');

var _TagList2 = _interopRequireDefault(_TagList);

var _style = require('./style.scss');

var _style2 = _interopRequireDefault(_style);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: 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 MultiSelect = function (_React$Component) {
  _inherits(MultiSelect, _React$Component);

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

    var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(MultiSelect).call(this, props));

    _this.state = {
      isOpen: false,
      value: _this.props.value || []
    };

    _this.componentWillMount = function () {
      // Set state
      if (_this.state.value instanceof Array && _this.state.value.length > 0 && _this.containsValidValue(_this.state.value, _this.props.options)) {
        _this.setState({ selected: _this.getSelectedOptions(_this.state.value), value: _this.state.value });
      }
      // No value is passed in
      else {
          _this.setState({ selected: [], value: [] });
        }
    };

    _this.componentWillReceiveProps = function (nextProps) {
      if (nextProps.value !== _this.state.value) {
        // Set state
        if (nextProps.value instanceof Array && (_this.containsValidValue(nextProps.value, nextProps.options) || nextProps.value.length === 0)) {
          _this.setState({ selected: _this.getSelectedOptions(nextProps.value), value: nextProps.value });
        }
        // No value is passed in
        else {
            _this.setState({ selected: [], value: [] });
          }
      }
    };

    _this.getIndex = function (value) {
      var optionIndex = -1;
      _this.props.options.map(function (option, index) {
        if (option[_this.props.valueProp] === value) {
          optionIndex = index;
        }
      });

      return optionIndex;
    };

    _this.containsValidValue = function (values, options) {
      var isValid = false;

      for (var i = 0; i < values.length; i++) {
        if (_this.getIndex(values[i], options) > -1) {
          isValid = true;
        }
      }

      return isValid;
    };

    _this.getSelectedOptions = function (values) {
      var selectedOptions = [];

      values.map(function (value, index) {
        _this.props.options.map(function (option, index) {
          if (option[_this.props.valueProp] === value) {
            selectedOptions.push(option);
          }
        });
      });

      return selectedOptions;
    };

    _this.filterItems = function () {
      var options = [];

      _this.props.options.map(function (option, index) {
        if (_this.state.value.indexOf(option[_this.props.valueProp]) === -1) {
          options.push(option);
        }
      });

      return options;
    };

    _this.handleChange = function (event) {
      // when value & option are empty it means that reset button was clicked
      if (event.target.value !== '' && event.target.option !== '') {
        var values = _this.state.value;
        values.push(event.target.value);

        _this.setState({ selected: _this.getSelectedOptions(values), value: values }, function () {
          if (_this.props.changeCallback) {
            _this.props.changeCallback({
              target: {
                name: _this.props.name,
                value: _this.state.value,
                options: _this.state.selected
              }
            });
          }
        });
      }
    };

    _this.onRemove = function (index) {
      var values = _this.state.value.slice();
      values.splice(index, 1);

      _this.setState({ selected: _this.getSelectedOptions(values), value: values }, function () {
        if (_this.props.changeCallback) {
          _this.props.changeCallback({
            target: {
              name: _this.props.name,
              value: _this.state.value,
              options: _this.state.selected
            }
          });
        }
      });
    };

    return _this;
  }

  _createClass(MultiSelect, [{
    key: 'getElements',
    value: function getElements(children) {
      var _props = this.props;
      var options = _props.options;
      var value = _props.value;

      var props = _objectWithoutProperties(_props, ['options', 'value']);

      props.options = this.filterItems();
      props.changeCallback = this.handleChange;

      if (['WrappedTypeahead', 'Wrappedt'].indexOf(children.type.displayName) !== -1) {
        props.resetAfterSelection = true;
      }

      return _react2.default.Children.map(children, function (child) {
        var _child$props = child.props;
        var options = _child$props.options;
        var value = _child$props.value;

        var childProps = _objectWithoutProperties(_child$props, ['options', 'value']);

        return _react2.default.cloneElement(child, _extends(childProps, props));
      });
    }
  }, {
    key: 'render',
    value: function render() {
      var multiSelectClasses = (0, _OptClass2.default)(_style2.default, 'multi-select', this.props.optClass);
      var elements = this.getElements(this.props.children);

      return _react2.default.createElement(
        'div',
        { className: multiSelectClasses },
        elements,
        _react2.default.createElement(_TagList2.default, { tags: this.state.selected, displayProp: this.props.displayProp, onRemove: this.onRemove })
      );
    }
  }]);

  return MultiSelect;
}(_react2.default.Component);

MultiSelect.defaultProps = {
  disabled: false
};
MultiSelect.propTypes = {
  /**
   * A string to display as the placeholder text.
   */
  placeholder: _react2.default.PropTypes.string,
  /**
   * An array of objects which will be used as the options for the MultiSelect component.
   */
  options: _react2.default.PropTypes.array.isRequired,
  /**
   * The values of the options to be selected.
   */
  value: _react2.default.PropTypes.array,
  /**
   * Which field in the option object will be used as the value of the MultiSelect component.
   */
  valueProp: _react2.default.PropTypes.string.isRequired,
  /**
   * Which field in the option object will be used as the display of the MultiSelect component.
   */
  displayProp: _react2.default.PropTypes.string.isRequired,
  /**
   * Whether the MultiSelect component is disabled.
   */
  disabled: _react2.default.PropTypes.bool,
  /**
   * A callback function to be called when an option is selected.
   */
  changeCallback: _react2.default.PropTypes.func,
  /**
   * Optional CSS class(es) to be used for local styles (string or array of strings)
   */
  optClass: _react2.default.PropTypes.oneOfType([_react2.default.PropTypes.array, _react2.default.PropTypes.string])
};
exports.default = MultiSelect;