'use strict';

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

var _react2 = _interopRequireDefault(_react);

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

var _propTypes2 = _interopRequireDefault(_propTypes);

var _index = require('../SelectBox/index');

var _index2 = _interopRequireDefault(_index);

var _InputTextTypeAhead = require('../InputTextTypeAhead');

var _InputTextTypeAhead2 = _interopRequireDefault(_InputTextTypeAhead);

var _ImagePromo = require('../../molecules/ImagePromo');

var _ImagePromo2 = _interopRequireDefault(_ImagePromo);

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

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

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

    _this.state = {
      selectedOrg: {}
    };
    _this.handleOrgSelectChange = _this.handleOrgSelectChange.bind(_this);
    _this.handleOrgTypeAheadChange = _this.handleOrgTypeAheadChange.bind(_this);
    return _this;
  }

  OrgSelector.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
    var input = nextProps.selectBox ? nextProps.selectBox : nextProps.typeAhead;
    var selectValue = input.options.find(function (element) {
      return element.text === input.selected;
    });
    if (selectValue !== undefined) {
      var selectedOrg = nextProps.organizations.filter(function (org) {
        return Object.prototype.hasOwnProperty.call(org, 'value') && org.value === selectValue.value;
      });
      if (selectedOrg.length > 0) {
        this.setState({
          selectedOrg: selectedOrg[0] // protect against multiple matches by returning the first
        });
        // If there is no org match, reset state so no orgInfo renders.
      } else {
        this.setState({
          selectedOrg: {}
        });
      }
    } else {
      this.setState({
        selectedOrg: {}
      });
    }
  };
  /**
   * Sets the selectedOrg to the item selected from the input, so <OrgInfo/>
   * knows what to render.
   *
   * @param input object
   *   @see SelectBox handleSelect method.
   */


  OrgSelector.prototype.handleOrgSelectChange = function handleOrgSelectChange(input) {
    var selectValue = input.suggestion ? input.suggestion : input;
    if (selectValue !== undefined) {
      var checkValue = input.suggestion ? selectValue.value : selectValue.selectedValue;
      var selectedOrg = this.props.organizations.filter(function (org) {
        return Object.prototype.hasOwnProperty.call(org, 'value') && org.value === checkValue;
      });
      if (selectedOrg.length > 0) {
        this.setState({
          selectedOrg: selectedOrg[0] // protect against multiple matches by returning the first
        });
        // If there is no org match, reset state so no orgInfo renders.
      } else {
        this.setState({
          selectedOrg: {}
        });
      }
    } else {
      this.setState({
        selectedOrg: {}
      });
    }
    if (typeof this.props.onChangeOrgCallback === 'function') {
      this.props.onChangeOrgCallback(input);
    }
  };

  OrgSelector.prototype.handleOrgTypeAheadChange = function handleOrgTypeAheadChange(event, input) {
    // Stop the filters form submission if enter is pressed in the selector.
    event.preventDefault();
    this.handleOrgSelectChange(input);
  };

  OrgSelector.prototype.render = function render() {
    var selectBoxProps = this.props.selectBox;
    var typeAheadProps = this.props.typeAhead;
    return _react2.default.createElement(
      'section',
      { className: 'ma__org-selector js-org-selector' },
      selectBoxProps && _react2.default.createElement(_index2.default, _extends({}, selectBoxProps, { onChangeCallback: this.handleOrgSelectChange })),
      typeAheadProps && _react2.default.createElement(_InputTextTypeAhead2.default, _extends({}, typeAheadProps, { onChange: this.handleOrgTypeAheadChange })),
      _react2.default.createElement(OrgInfo, { org: this.state.selectedOrg })
    );
  };

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

/**
 * Porting over handlebars template for orgInfo
 * @see https://github.com/massgov/mayflower/blob/dev/styleguide/source/assets/js/templates/orgInfo.html
 */


var OrgInfo = function OrgInfo(props) {
  var org = props.org;
  if (Object.keys(org).length > 0 && Object.prototype.hasOwnProperty.call(org, 'value')) {
    return _react2.default.createElement(
      'div',
      { className: 'ma__org-selector__org-info js-org-info' },
      _react2.default.createElement(
        'section',
        { className: 'ma__org-info' },
        _react2.default.createElement(_ImagePromo2.default, {
          title: {
            href: org.name.href,
            text: org.name.text
          },
          tags: null,
          image: {
            alt: org.image.alt,
            src: org.image.src,
            height: org.image.height,
            width: org.image.width
          },
          stacked: true,
          small: true,
          subTitle: org.jobTitle,
          description: org.message,
          link: {
            text: org.moreLink.text,
            href: org.moreLink.href,
            info: org.moreLink.info
          }
        })
      )
    );
  }
  return false;
};

/** An object which has the image, name, title, description, and link to an org.  */
OrgInfo.propTypes = process.env.NODE_ENV !== "production" ? _ImagePromo2.default.propTypes : {};

OrgSelector.propTypes = process.env.NODE_ENV !== "production" ? {
  /** @forms/SelectBox  */
  selectBox: _propTypes2.default.shape(_index2.default.propTypes),
  /** @forms/InputTextTypeAhead  */
  typeAhead: _propTypes2.default.shape(_InputTextTypeAhead2.default.propTypes),
  /** An array of objects of org info which renders (as <OrgInfo/>) when that org is selected  */
  organizations: _propTypes2.default.arrayOf(_propTypes2.default.shape(OrgInfo.propTypes)),
  /** A custom function users can add for when onchange is triggered */
  onChangeOrgCallback: _propTypes2.default.func
} : {};

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