'use strict';

exports.__esModule = true;

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

require('./style.css');

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

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

    var _this = _possibleConstructorReturn(this, _React$Component.call(this, props));

    _this.state = {
      selected: !props.selected ? props.options[0].text : props.selected
    };
    _this.handleOnChange = _this.handleOnChange.bind(_this);
    return _this;
  }

  SelectBox.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
    this.setState({ selected: nextProps.selected });
  };
  /**
   * Default event handler which renders selected item in the patter div.
   *
   * @param event The DOM onChange event
   *
   * Invokes custom callback passed as prop onChangeCallback, passing back the
   * object with select information.
   */


  SelectBox.prototype.handleOnChange = function handleOnChange(event) {
    var selectedIndex = event.nativeEvent.target.selectedIndex;
    var selected = event.target[selectedIndex].text;
    var selectedValue = event.target[selectedIndex].value;
    this.setState({ selected: selected });

    // invokes custom function if passed in the component
    if (typeof this.props.onChangeCallback === 'function') {
      this.props.onChangeCallback({ selectedIndex: selectedIndex, selected: selected, selectedValue: selectedValue });
    }
  };

  SelectBox.prototype.render = function render() {
    var classNames = '';
    if (this.props.className) {
      classNames = this.props.className;
    } else {
      classNames = !this.props.required ? 'ma__select-box js-dropdown ma__select-box--optional' : 'ma__select-box js-dropdown';
    }
    var selectClassNames = this.props.required ? 'ma__select-box__select js-dropdown-select js-required' : 'ma__select-box__select js-dropdown-select';
    var selected = this.state.selected;
    var stackLabel = this.props.stackLabel;

    var labelClassNames = stackLabel ? 'ma__select-box__label' : 'ma__label--inline ma__label--small';
    var selectBoxInline = stackLabel ? '' : 'ma__select-box__field--inline';
    var getValueByText = function getValueByText() {
      var array = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
      var text = arguments[1];

      var matchedItem = array.find(function (item) {
        return item.text === text;
      });
      var matchedValue = matchedItem && matchedItem.value;
      return matchedValue;
    };
    var valueInOptions = getValueByText(this.props.options, selected);
    var selectedValue = valueInOptions || this.props.options[0].value;
    return _react2.default.createElement(
      'section',
      { className: classNames },
      _react2.default.createElement(
        'label',
        { htmlFor: this.props.id, className: labelClassNames },
        this.props.label
      ),
      _react2.default.createElement(
        'div',
        { className: 'ma__select-box__field ' + selectBoxInline },
        _react2.default.createElement(
          'select',
          {
            name: this.props.id,
            id: this.props.id,
            className: selectClassNames,
            onChange: this.handleOnChange,
            value: selectedValue
          },
          this.props.options.map(function (option) {
            return _react2.default.createElement(
              'option',
              { key: option.value, value: option.value },
              option.text
            );
          })
        ),
        _react2.default.createElement(
          'div',
          { className: 'ma__select-box__link' },
          _react2.default.createElement(
            'span',
            { className: 'js-dropdown-link' },
            valueInOptions ? selected : this.props.options[0].text
          ),
          _react2.default.createElement('span', { className: 'ma__select-box__icon' })
        )
      )
    );
  };

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

SelectBox.propTypes = process.env.NODE_ENV !== "production" ? {
  /** The label text above the select box */
  label: _propTypes2.default.string.isRequired,
  /** Whether to stack label or inline label */
  stackLabel: _propTypes2.default.bool,
  /** Whether the form field is required or not */
  required: _propTypes2.default.bool,
  /** The id of the selectbox element */
  id: _propTypes2.default.string.isRequired,
  /** An array of options for the selectbox */
  options: _propTypes2.default.arrayOf(_propTypes2.default.shape({
    value: _propTypes2.default.oneOfType([_propTypes2.default.string]),
    text: _propTypes2.default.oneOfType([_propTypes2.default.string])
  })),
  /** Change handler callback provided by the parent */
  onChangeCallback: _propTypes2.default.func,
  /** Wrapper class for section tag */
  className: _propTypes2.default.string,
  /** The default value for the select box */
  selected: _propTypes2.default.string
} : {};

SelectBox.defaultProps = {
  required: false
};

exports.default = SelectBox;
module.exports = exports['default'];