'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 _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _FieldRowContainer = require('./styles/FieldRowContainer');

var _FieldRowContainer2 = _interopRequireDefault(_FieldRowContainer);

var _FieldRow = require('./styles/FieldRow');

var _FieldRow2 = _interopRequireDefault(_FieldRow);

var _Field = require('./Field');

var _Field2 = _interopRequireDefault(_Field);

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

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

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

  function Fields() {
    var _ref;

    var _temp, _this, _ret;

    _classCallCheck(this, Fields);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Fields.__proto__ || Object.getPrototypeOf(Fields)).call.apply(_ref, [this].concat(args))), _this), _this.partitionFields = function () {
      var _this$props = _this.props,
          columns = _this$props.columns,
          children = _this$props.children,
          Row = _this$props.Row;

      var childArray = _react2.default.Children.toArray(children);

      var rows = childArray.reduce(function (rows, child) {
        var childColumnSpan = child.props.columnSpan || 1;

        if (childColumnSpan > columns) {
          throw new Error('A Field has a columnSpan of ' + childColumnSpan + ', but the containing Fields only has ' + columns + ' columns');
        }

        var currentRow = rows[rows.length - 1];
        if (currentRow.columnWidth + childColumnSpan <= columns) {
          // add to current row
          return [].concat(_toConsumableArray(rows.slice(0, rows.length - 1)), [{
            children: [].concat(_toConsumableArray(currentRow.children), [{
              column: currentRow.columnWidth,
              element: child
            }]),
            columnWidth: currentRow.columnWidth + childColumnSpan
          }]);
        } else {
          // create new row
          return [].concat(_toConsumableArray(rows), [{
            children: [{ column: 0, element: child }],
            columnWidth: childColumnSpan
          }]);
        }
      }, [{ children: [], columnWidth: 0 }]);

      return rows.map(function (row, rowIdx) {
        return _react2.default.createElement(
          Row,
          { key: rowIdx, columns: columns },
          row.children.map(function (_ref2) {
            var element = _ref2.element,
                column = _ref2.column;
            return _react2.default.cloneElement(element, { column: column });
          })
        );
      });
    }, _temp), _possibleConstructorReturn(_this, _ret);
  }

  _createClass(Fields, [{
    key: 'render',
    value: function render() {
      var RowContainer = this.props.RowContainer;


      return _react2.default.createElement(
        RowContainer,
        null,
        this.partitionFields()
      );
    }
  }]);

  return Fields;
}(_react2.default.PureComponent);

Fields.Field = _Field2.default;
Fields.propTypes = {
  /**
   * The number of columns to divide the fieldset into when rendering. Fields can span multiple columns if provided
   * with a columnSpan prop. Fields which overflow the column limit will be added to new rows. If a Field's
   * columnSpan is too large to fit in the current row, it will be wrapped to the next one.
   */
  columns: _propTypes2.default.number,
  /**
   * A component prop to override the component used to render the outer container which renders field rows.
   * Defaults to FieldRowContainer.
   */
  RowContainer: _propTypes2.default.func,
  /**
   * A component prop to override the component which is injected to wrap Field elements into discrete rows.
   * Row receives the same `columns` prop provided to this component. Defaults to FieldRow.
   */
  Row: _propTypes2.default.func
};
Fields.defaultProps = {
  RowContainer: _FieldRowContainer2.default,
  Row: _FieldRow2.default,
  columns: 2
};
exports.default = Fields;