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

var _react2 = _interopRequireDefault(_react);

var _bind = require('classnames/bind');

var _bind2 = _interopRequireDefault(_bind);

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

var _style2 = _interopRequireDefault(_style);

var _Icon = require('../Icon');

var _Icon2 = _interopRequireDefault(_Icon);

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

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 SelectField = function (_React$Component) {
  _inherits(SelectField, _React$Component);

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

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

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

    _this.componentWillMount = function () {
      if (typeof _this.state.value !== 'undefined' && _this.state.value !== '') {
        _this.selectItem(_this.state.value, _this.props.options);
      } else {
        _this.setState({ selected: '' });
      }
    };

    _this.componentWillUnmount = function () {
      document.removeEventListener('click', _this.toggleSelectField);
    };

    _this.componentWillReceiveProps = function (nextProps) {
      if (nextProps.value && nextProps.value !== _this.state.value) {
        _this.setState({ value: nextProps.value }, function () {
          this.selectItem(nextProps.value, nextProps.options);
        });
      }
    };

    _this.toggleSelectField = function () {
      _this.setState({ isOpen: !_this.state.isOpen }, function () {
        if (this.state.isOpen) {
          document.addEventListener('click', this.toggleSelectField);
        } else {
          document.removeEventListener('click', this.toggleSelectField);
        }
      });
    };

    _this.selectOption = function (option) {
      _this.setState({ selected: option, value: option.value }, function () {
        if (typeof this.props.changeCallback === 'function') {
          this.props.changeCallback({
            target: {
              name: this.props.name,
              value: option[this.props.valueProp],
              option: option
            }
          });
        }
      });
    };

    _this.selectItem = function (value, options) {
      var index = _this.getIndex(value, options);
      if (index >= 0) {
        _this.selectOption(options[index]);
      }
    };

    _this.getIndex = function (value, options) {
      var optionIndex = -1;
      options.map(function (radio, index) {
        if (radio.value === value) {
          optionIndex = index;
        }
      });

      return optionIndex;
    };

    _this.getDisplayText = function () {
      if (_this.state.selected !== '') {
        return _this.state.selected[_this.props.displayProp];
      } else if (typeof _this.props.placeholder !== 'undefined') {
        return _this.props.placeholder;
      } else {
        return _this.props.options[0][_this.props.displayProp];
      }
    };

    return _this;
  }

  _createClass(SelectField, [{
    key: 'render',
    value: function render() {
      var _this2 = this;

      var cx = _bind2.default.bind(_style2.default);
      var disabledClass = this.props.disabled ? _style2.default['selectfield-disabled'] : '';
      var activeClass = this.state.isOpen ? _style2.default['active'] : null;
      var selectFieldClass = cx(_style2.default['selectfield-component'], activeClass, disabledClass, this.props.optClass);

      var options = this.props.options.map(function (option, index) {
        return _react2.default.createElement(
          'li',
          { key: index, onClick: _this2.selectOption.bind(null, option) },
          option[_this2.props.displayProp]
        );
      });

      return _react2.default.createElement(
        'div',
        { className: selectFieldClass },
        _react2.default.createElement('input', { type: 'hidden', name: 'selectfield-value', value: this.state.selected && this.state.selected[this.props.valueProp] }),
        _react2.default.createElement(
          'div',
          { className: _style2.default['selectfield-value'], onClick: this.toggleSelectField },
          this.getDisplayText(),
          _react2.default.createElement(_Icon2.default, { name: 'icon-caret', width: '10', height: '10' }),
          _react2.default.createElement(
            'ul',
            null,
            options
          )
        )
      );
    }
  }]);

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

SelectField.defaultProps = {
  disabled: false
};
SelectField.propTypes = {
  /**
   * A string to display as the placeholder text.
   */
  placeholder: _react2.default.PropTypes.string,
  /**
   * An array objects that which will be used as the options for the select field.
   */
  options: _react2.default.PropTypes.array.isRequired,
  /**
   * The value of the option to be selected.
   */
  value: _react2.default.PropTypes.string,
  /**
   * Which field in the option object will be used as the value of the select field.
   */
  valueProp: _react2.default.PropTypes.string.isRequired,
  /**
   * Which field in the option object will be used as the display of the select field.
   */
  displayProp: _react2.default.PropTypes.string.isRequired,
  /**
   * Whether the select field is disabled.
   */
  disabled: _react2.default.PropTypes.bool,
  /**
   * Optional styles to add to the select field.
   */
  optClass: _react2.default.PropTypes.string,
  /**
   * A callback function to be called when an option is selected.
   */
  changeCallback: _react2.default.PropTypes.func
};
exports.default = SelectField;