'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 _debounce = require('lodash/debounce');

var _debounce2 = _interopRequireDefault(_debounce);

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

var _style2 = _interopRequireDefault(_style);

var _OptClass = require('../internal/OptClass');

var _OptClass2 = _interopRequireDefault(_OptClass);

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.setState({ fields: _this.props.schema });
    };

    _this.handleSubmit = function (event) {
      event.preventDefault();
      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;

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

    _this.renderForm = function () {
      var elements = _this.getElements(_this.props.children);
      var formGroupClass = (0, _OptClass2.default)(_style2.default, 'form-group', _this.props.optClass);
      var formWrapper = void 0;

      if (!_this.props.nested) {
        formWrapper = _react2.default.createElement(
          'form',
          { className: formGroupClass, onSubmit: _this.handleSubmit },
          _react2.default.createElement(
            'fieldset',
            { className: _style2.default.fieldset },
            elements
          )
        );
      } else {
        var fieldsetClass = (0, _OptClass2.default)(_style2.default, 'fieldset', _this.props.optClass);
        formWrapper = _react2.default.createElement(
          'fieldset',
          { className: fieldsetClass },
          elements
        );
      }
      return formWrapper;
    };

    _this.debounce = (0, _debounce2.default)(_this.handleChange, _this.props.debounceTime);
    return _this;
  }

  _createClass(FormGroup, [{
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps) {
      this.setState({
        fields: 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.props.debounceTime ? _this2.debounce : _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() {
      return this.renderForm();
    }
  }]);

  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,
  /**
   * Optional CSS class(es) to be used for local styles (string or array of strings)
   */
  optClass: _react2.default.PropTypes.oneOfType([_react2.default.PropTypes.array, _react2.default.PropTypes.string]),
  /**
   * Option to turn off form wrapper (for nested components)
   */
  nested: _react2.default.PropTypes.bool,
  /**
   * Option to turn off debounce when something in the form group changes
   */
  debounceTime: _react2.default.PropTypes.number
};
FormGroup.defaultProps = {
  debounceTime: 0
};
exports.default = FormGroup;