'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 _style = require('./style.scss');

var _style2 = _interopRequireDefault(_style);

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

var _bind2 = _interopRequireDefault(_bind);

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

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

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

    _this.componentWillMount = function () {
      _this.setInitialState();
    };

    _this.setInitialState = function () {
      var fields = {};
      var value = null;
      var schema = _this.props.schema;

      for (value in schema) {
        fields[value] = schema[value];
      }

      _this.setState({ fields: fields });
    };

    _this.handleSubmit = function (event) {
      if (typeof _this.props.submitCallback === 'function') {
        _this.props.submitCallback(event, _this.state.fields);
      }
    };

    _this.handleChange = function (event) {
      var val = void 0;

      if (event.target.type === 'checkbox') {
        val = event.target.value === 'false' ? false : true;
      } else {
        val = event.target.value;
      }

      var newField = _extends({}, _this.state.fields[event.target.name], { value: val });
      var previousState = _extends({}, _this.state);
      var newState = previousState.fields[event.target.name] = newField;

      _this.setState(newState, function () {
        if (typeof this.props.changeCallback === 'function') {
          this.props.changeCallback(this.state.fields);
        }
      });
    };

    return _this;
  }

  _createClass(FormGroup, [{
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps) {
      this.state.schema = nextProps.schema;
    }
  }, {
    key: 'getElements',
    value: function getElements(children) {
      var _this2 = this;

      return _react2.default.Children.map(children, function (child) {
        var childProps = {};
        if (child.props) {
          var name = child.props.name;
          var fields = _this2.state.fields;

          if (name in fields) {
            if (_react2.default.isValidElement(child)) {
              childProps = {
                changeCallback: _this2.handleChange,
                value: fields[name].value
              };
            }
          }

          childProps.children = _this2.getElements(child.props.children);
          return _react2.default.cloneElement(child, childProps);
        }
        return child;
      });
    }
  }, {
    key: 'render',
    value: function render() {
      var cx = _bind2.default.bind(_style2.default);
      var formGroupClass = cx(_style2.default['form-group'], this.props.optClass);

      var elements = this.getElements(this.props.children);

      return _react2.default.createElement(
        'form',
        { className: formGroupClass, onSubmit: this.handleSubmit },
        _react2.default.createElement(
          'fieldset',
          { className: _style2.default.fieldset },
          elements
        )
      );
    }
  }]);

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

FormGroup.propTypes = {
  /**
   * A configuration object of name/value pairs
   * that correspond to the form fields names.
   */
  schema: _react2.default.PropTypes.object,
  /**
   * A callback function to be called when a form value changes.
   */
  changeCallback: _react2.default.PropTypes.func,
  /**
   * A callback function to be called when the form is submitted.
   */
  submitCallback: _react2.default.PropTypes.func,
  /**
   * An optional CSS class to be used for local styles
   */
  optClass: _react2.default.PropTypes.string
};
exports.default = FormGroup;