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

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


const renderMessageLabel = (message, props) => _react2.default.createElement(
  Label,
  props,
  _react2.default.createElement(_reactIntl.FormattedMessage, message)
);

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

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

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

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

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

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

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


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

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

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

  const tableLabel = renderTableLabel(recordTypeConfig, name);

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

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