'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; };

exports.default = repeatable;

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _RepeatingInput = require('../components/RepeatingInput');

var _RepeatingInput2 = _interopRequireDefault(_RepeatingInput);

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

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

/**
 * Makes an input component possibly repeating. Returns an enhanced component that accepts a
 * repeating prop. If true, the base component is wrapped in a RepeatingInput; otherwise, the
 * base component is returned unchanged.
 * @param {string|function} BaseComponent - The component to enhance.
 * @returns {function} The enhanced component.
 */
function repeatable(BaseComponent) {
  var baseComponentName = BaseComponent.displayName || BaseComponent.name || 'Component';

  var propTypes = _extends({}, BaseComponent.propTypes, _RepeatingInput2.default.propTypes, {
    repeating: _react.PropTypes.bool
  });

  function Repeatable(props) {
    var repeating = props.repeating,
        onAddInstance = props.onAddInstance,
        onMoveInstance = props.onMoveInstance,
        onRemoveInstance = props.onRemoveInstance,
        remainingProps = _objectWithoutProperties(props, ['repeating', 'onAddInstance', 'onMoveInstance', 'onRemoveInstance']);

    if (!repeating) {
      return _react2.default.createElement(BaseComponent, remainingProps);
    }

    var name = remainingProps.name,
        parentPath = remainingProps.parentPath,
        subpath = remainingProps.subpath,
        value = remainingProps.value,
        onCommit = remainingProps.onCommit,
        baseProps = _objectWithoutProperties(remainingProps, ['name', 'parentPath', 'subpath', 'value', 'onCommit']);

    return _react2.default.createElement(
      _RepeatingInput2.default,
      {
        name: name,
        parentPath: parentPath,
        subpath: subpath,
        value: value,
        onAddInstance: onAddInstance,
        onCommit: onCommit,
        onMoveInstance: onMoveInstance,
        onRemoveInstance: onRemoveInstance
      },
      _react2.default.createElement(BaseComponent, baseProps)
    );
  }

  Repeatable.propTypes = propTypes;
  Repeatable.displayName = 'repeatable(' + baseComponentName + ')';

  return Repeatable;
}