'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 _immutable = require('immutable');

var _immutable2 = _interopRequireDefault(_immutable);

var _MiniButton = require('./MiniButton');

var _MiniButton2 = _interopRequireDefault(_MiniButton);

var _normalizeLabel = require('../helpers/normalizeLabel');

var _normalizeLabel2 = _interopRequireDefault(_normalizeLabel);

var _pathHelpers = require('../helpers/pathHelpers');

var _RepeatingInput = require('../../styles/cspace-input/RepeatingInput.css');

var _RepeatingInput2 = _interopRequireDefault(_RepeatingInput);

var _MoveToTopButton = require('../../styles/cspace-input/MoveToTopButton.css');

var _MoveToTopButton2 = _interopRequireDefault(_MoveToTopButton);

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

function normalizeValue(value) {
  var defaultValue = [undefined];

  if (!value) {
    return defaultValue;
  }

  var normalized = void 0;

  if (Array.isArray(value)) {
    normalized = value;
  } else if (_immutable2.default.List.isList(value)) {
    normalized = value.toArray();
  } else {
    normalized = [value];
  }

  if (normalized.length === 0) {
    return defaultValue;
  }

  return normalized;
}

var propTypes = {
  children: _react.PropTypes.node,
  name: _react.PropTypes.string,
  parentPath: _pathHelpers.pathPropType, // eslint-disable-line react/no-unused-prop-types
  subpath: _pathHelpers.pathPropType, // eslint-disable-line react/no-unused-prop-types
  value: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.object, _react.PropTypes.instanceOf(_immutable2.default.List), _react.PropTypes.arrayOf(_react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.object]))]),
  onAddInstance: _react.PropTypes.func,
  onCommit: _react.PropTypes.func,
  onMoveInstance: _react.PropTypes.func,
  onRemoveInstance: _react.PropTypes.func
};

var RepeatingInput = function (_Component) {
  _inherits(RepeatingInput, _Component);

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

    var _this = _possibleConstructorReturn(this, (RepeatingInput.__proto__ || Object.getPrototypeOf(RepeatingInput)).call(this, props));

    _this.handleInstanceCommit = _this.handleInstanceCommit.bind(_this);
    _this.handleAddButtonClick = _this.handleAddButtonClick.bind(_this);
    _this.handleMoveToTopButtonClick = _this.handleMoveToTopButtonClick.bind(_this);
    _this.handleRemoveButtonClick = _this.handleRemoveButtonClick.bind(_this);
    return _this;
  }

  _createClass(RepeatingInput, [{
    key: 'handleAddButtonClick',
    value: function handleAddButtonClick() {
      var onAddInstance = this.props.onAddInstance;


      if (onAddInstance) {
        onAddInstance((0, _pathHelpers.getPath)(this.props));
      }
    }
  }, {
    key: 'handleInstanceCommit',
    value: function handleInstanceCommit(instancePath, value) {
      var onCommit = this.props.onCommit;


      if (onCommit) {
        onCommit(instancePath, value);
      }
    }
  }, {
    key: 'handleMoveToTopButtonClick',
    value: function handleMoveToTopButtonClick(event) {
      var onMoveInstance = this.props.onMoveInstance;


      if (onMoveInstance) {
        var instanceName = event.target.dataset.instancename;
        var newPosition = 0;

        onMoveInstance([].concat(_toConsumableArray((0, _pathHelpers.getPath)(this.props)), [instanceName]), newPosition);
      }
    }
  }, {
    key: 'handleRemoveButtonClick',
    value: function handleRemoveButtonClick(event) {
      var onRemoveInstance = this.props.onRemoveInstance;


      if (onRemoveInstance) {
        var instanceName = event.target.dataset.instancename;

        onRemoveInstance([].concat(_toConsumableArray((0, _pathHelpers.getPath)(this.props)), [instanceName]));
      }
    }
  }, {
    key: 'renderHeader',
    value: function renderHeader() {
      var children = this.props.children;


      var template = _react2.default.Children.only(children);

      var label = template.props.label;


      var normalizedLabel = (0, _normalizeLabel2.default)(label);

      if (!label) {
        return null;
      }

      return _react2.default.createElement(
        'header',
        null,
        _react2.default.createElement('div', null),
        _react2.default.createElement(
          'div',
          null,
          normalizedLabel
        ),
        _react2.default.createElement('div', null)
      );
    }
  }, {
    key: 'renderInstances',
    value: function renderInstances() {
      var _this2 = this;

      var _props = this.props,
          children = _props.children,
          value = _props.value;


      var template = _react2.default.Children.only(children);

      return normalizeValue(value).map(function (instanceValue, index, list) {
        var instanceName = '' + index;

        var overrideProps = {
          embedded: true,
          label: undefined,
          name: instanceName,
          parentPath: (0, _pathHelpers.getPath)(_this2.props),
          value: instanceValue,
          // The template is expected to accept an onCommit prop.
          onCommit: _this2.handleInstanceCommit
        };

        var instance = _react2.default.cloneElement(template, overrideProps);

        return _react2.default.createElement(
          'div',
          { key: index },
          _react2.default.createElement(
            'div',
            null,
            _react2.default.createElement(
              _MiniButton2.default,
              {
                className: _MoveToTopButton2.default.common,
                'data-instancename': instanceName,
                disabled: index === 0,
                name: 'moveToTop',
                onClick: _this2.handleMoveToTopButtonClick
              },
              index + 1
            )
          ),
          _react2.default.createElement(
            'div',
            null,
            instance
          ),
          _react2.default.createElement(
            'div',
            null,
            _react2.default.createElement(
              _MiniButton2.default,
              {
                'data-instancename': instanceName,
                disabled: list.length < 2,
                name: 'remove',
                onClick: _this2.handleRemoveButtonClick
              },
              '\u2212'
            )
          )
        );
      });
    }
  }, {
    key: 'render',
    value: function render() {
      var name = this.props.name;


      var header = this.renderHeader();
      var instances = this.renderInstances();

      return _react2.default.createElement(
        'fieldset',
        {
          className: _RepeatingInput2.default.common,
          name: name
        },
        _react2.default.createElement(
          'div',
          null,
          header,
          instances
        ),
        _react2.default.createElement(
          'footer',
          null,
          _react2.default.createElement(
            'div',
            null,
            _react2.default.createElement(
              _MiniButton2.default,
              {
                name: 'add',
                onClick: this.handleAddButtonClick
              },
              '+'
            )
          )
        )
      );
    }
  }]);

  return RepeatingInput;
}(_react.Component);

exports.default = RepeatingInput;


RepeatingInput.propTypes = propTypes;