'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 _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactSelect = require('react-select');

var _reactSelect2 = _interopRequireDefault(_reactSelect);

var _omit = require('lodash/omit');

var _omit2 = _interopRequireDefault(_omit);

var _FieldControl = require('../FieldControl');

var _FieldControl2 = _interopRequireDefault(_FieldControl);

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

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

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; } /* eslint-disable react/no-danger */


/**
 * Input Select
 *
 */
var SelectInput = function (_React$Component) {
  _inherits(SelectInput, _React$Component);

  function SelectInput() {
    var _ref;

    var _temp, _this, _ret;

    _classCallCheck(this, SelectInput);

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

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = SelectInput.__proto__ || Object.getPrototypeOf(SelectInput)).call.apply(_ref, [this].concat(args))), _this), _this.state = {
      options: []
    }, _this.onChange = function (nextValue) {
      var _this$getInputProps = _this.getInputProps(),
          onChange = _this$getInputProps.onChange;

      _this.updateOptions({ nextValue: nextValue });
      if (typeof onChange === 'function') {
        if (Array.isArray(nextValue)) {
          onChange(nextValue.map(function (i) {
            return i.value;
          }));
        } else {
          onChange(nextValue ? nextValue.value : null);
        }
      }
    }, _this.onBlur = function () {
      var _this$getInputProps2 = _this.getInputProps(),
          value = _this$getInputProps2.value,
          onBlur = _this$getInputProps2.onBlur;

      if (typeof onBlur === 'function') {
        onBlur(value);
      }
    }, _temp), _possibleConstructorReturn(_this, _ret);
  }

  _createClass(SelectInput, [{
    key: 'componentWillMount',
    value: function componentWillMount() {
      this.updateOptions();
    }
  }, {
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps) {
      this.updateOptions({ props: nextProps });
    }
  }, {
    key: 'getInputProps',
    value: function getInputProps(props) {
      var _ref2 = props || this.props,
          input = _ref2.input,
          resultProps = _objectWithoutProperties(_ref2, ['input']);

      return _extends({}, resultProps, input);
    }
  }, {
    key: 'updateOptions',
    value: function updateOptions() {
      var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
          props = _ref3.props,
          nextValue = _ref3.nextValue;

      var resultProps = props || this.props;
      var options = resultProps.options,
          allowCreate = resultProps.allowCreate,
          multi = resultProps.multi;

      var parsedOptions = Array.isArray(options) ? [].concat(_toConsumableArray(options)) : Object.keys(options).map(function (key) {
        return { value: key, label: options[key] };
      });
      if (allowCreate && multi) {
        var resultValue = nextValue || this.getInputProps(resultProps).value;
        var objectOption = Array.isArray(options) ? options.reduce(function (resultObject, _ref4) {
          var value = _ref4.value,
              label = _ref4.label;

          // eslint-disable-next-line no-param-reassign
          resultObject[value] = label;
          return resultObject;
        }, {}) || {} : options;

        if (Array.isArray(resultValue)) {
          resultValue.forEach(function (itemValue) {
            if (!objectOption[itemValue]) {
              parsedOptions.push({ value: itemValue, label: itemValue });
            }
          });
        }
      }
      this.setState({ options: parsedOptions });
    }
  }, {
    key: 'render',
    value: function render() {
      var _this2 = this;

      var _props = this.props,
          childrenClassName = _props.childrenClassName,
          allowCreate = _props.allowCreate,
          placeholder = _props.placeholder,
          props = _objectWithoutProperties(_props, ['childrenClassName', 'allowCreate', 'placeholder']);

      var options = this.state.options;


      var ResultSelect = allowCreate && this.props.multi ? _reactSelect.Creatable : _reactSelect2.default;

      return _react2.default.createElement(
        _FieldControl2.default,
        props,
        function (restProps) {
          return _react2.default.createElement(ResultSelect, _extends({
            className: childrenClassName,
            options: options,
            onChange: _this2.onChange,
            onBlur: _this2.onBlur,
            placeholder: placeholder
          }, (0, _omit2.default)(_this2.getInputProps(restProps), ['options', 'onChange', 'onBlur'])));
        }
      );
    }
  }]);

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

SelectInput.propTypes = {
  // eslint-disable-next-line react/no-unused-prop-types
  options: _propTypes2.default.oneOfType([_propTypes2.default.object, _propTypes2.default.array]),
  /**
   * Allow multiple choices
   */
  multi: _propTypes2.default.bool,
  childrenClassName: _propTypes2.default.string,
  // eslint-disable-next-line react/no-unused-prop-types
  input: _propTypes2.default.object,
  placeholder: _propTypes2.default.string,
  /**
   * Allow user to create new tags in multiple select input
   */
  allowCreate: _propTypes2.default.bool
};
SelectInput.defaultProps = {
  options: [],
  multi: false,
  childrenClassName: '',
  touched: false,
  allowCreate: false,
  placeholder: 'Select...',
  input: null
};
exports.default = SelectInput;
module.exports = exports['default'];