'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = InputTable;

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactIntl = require('react-intl');

var _get = require('lodash/get');

var _get2 = _interopRequireDefault(_get);

var _cspaceInput = require('cspace-input');

var _configHelpers = require('../../helpers/configHelpers');

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

var Label = _cspaceInput.components.Label,
    BaseInputTable = _cspaceInput.components.InputTable;
var pathHelpers = _cspaceInput.helpers.pathHelpers;


var renderMessageLabel = function renderMessageLabel(message, props) {
  return _react2.default.createElement(
    Label,
    props,
    _react2.default.createElement(_reactIntl.FormattedMessage, message)
  );
};

var renderTableLabel = function renderTableLabel(recordTypeConfig, name) {
  var message = (0, _get2.default)(recordTypeConfig, ['messages', 'inputTable', name]);

  return message ? renderMessageLabel(message) : null;
};

var renderFieldLabel = function renderFieldLabel(fieldConfig, inputProps) {
  var message = (0, _get2.default)(fieldConfig, ['messages', 'name']);

  var props = {
    readOnly: inputProps.readOnly,
    required: inputProps.required
  };

  if ('readOnly' in fieldConfig) {
    props.readOnly = fieldConfig.readOnly;
  }

  if ('required' in fieldConfig) {
    props.required = fieldConfig.required;
  }

  return message ? renderMessageLabel(message, props) : null;
};

var propTypes = {
  children: _propTypes2.default.node,
  name: _propTypes2.default.string
};

var contextTypes = {
  config: _propTypes2.default.object,
  recordType: _propTypes2.default.string
};

function InputTable(props, context) {
  var children = props.children,
      name = props.name;
  var config = context.config,
      recordType = context.recordType;


  var recordTypeConfig = (0, _get2.default)(config, ['recordTypes', recordType]);
  var fields = (0, _get2.default)(recordTypeConfig, 'fields');

  var renderLabel = function renderLabel(input) {
    var path = (0, _configHelpers.dataPathToFieldDescriptorPath)(pathHelpers.getPath(input.props));
    var field = (0, _get2.default)(fields, path);
    var fieldConfig = (0, _get2.default)(field, _configHelpers.configKey);

    return renderFieldLabel(fieldConfig, input.props);
  };

  var tableLabel = renderTableLabel(recordTypeConfig, name);

  return _react2.default.createElement(
    BaseInputTable,
    { label: tableLabel, renderLabel: renderLabel },
    children
  );
}

InputTable.propTypes = propTypes;
InputTable.contextTypes = contextTypes;