"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.formatHumanReadable = exports.default = exports.ConnectedFieldTextContainer = void 0;
var _propTypes = _interopRequireDefault(require("prop-types"));
var _reactRedux = require("react-redux");
var _cspaceInput = require("cspace-input");
var _reactIntl = require("react-intl");
var _formatHelpers = require("../../helpers/formatHelpers");
var _withConfig = _interopRequireDefault(require("../../enhancers/withConfig"));
var _withCsid = _interopRequireDefault(require("../../enhancers/withCsid"));
var _reducers = require("../../reducers");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const {
  TextInput
} = _cspaceInput.components;
const propTypes = {
  csid: _propTypes.default.string,
  intl: _reactIntl.intlShape,
  config: _propTypes.default.object,
  value: _propTypes.default.string
};
const formatHumanReadable = (type, value, context) => {
  let formatted;

  // the key is created with schema:fieldName:listIndex
  // we have 3 outcomes -- an array of index 1 (unqualified), 2 (qualified), or 3 (qualified list)
  // see: AuditDocumentHandler.java
  const parts = value.split(':');
  if (parts.length === 2) {
    formatted = (0, _formatHelpers.formatRecordTypeSourceField)(type, value, context);
  } else if (parts.length === 3) {
    // todo: get child of the key
    formatted = (0, _formatHelpers.formatRecordTypeSourceField)(type, `${parts[0]}:${parts[1]}`, context);
  } else {
    formatted = value;
  }

  // when the fieldConfig isn't found, the return is of the form [${fieldName}], which is
  // less readable than the value itself
  return formatted[0] === '[' ? value : formatted;
};
exports.formatHumanReadable = formatHumanReadable;
const mapStateToProps = (state, ownProps) => {
  const {
    intl,
    csid,
    config,
    value
  } = ownProps;
  let formattedValue;
  const recordData = (0, _reducers.getRecordData)(state, csid);
  if (recordData && value) {
    const auditedType = recordData.getIn(['ns3:audit_common', 'resourceType']).toLowerCase();
    formattedValue = formatHumanReadable(auditedType, value, {
      intl,
      config
    });
  }
  return {
    value: formattedValue || value
  };
};

/**
 * trim out props not needed for TextInput
 */
const mergeProps = (stateProps, _dispatchProps, ownProps) => {
  const {
    intl,
    csid,
    config,
    value,
    ...remainingProps
  } = ownProps;
  return {
    ...stateProps,
    ...remainingProps
  };
};
const ConnectedFieldTextContainer = (0, _reactRedux.connect)(mapStateToProps, null, mergeProps)(TextInput);
exports.ConnectedFieldTextContainer = ConnectedFieldTextContainer;
const EnhancedFieldTextContainer = (0, _reactIntl.injectIntl)((0, _withConfig.default)((0, _withCsid.default)(ConnectedFieldTextContainer)));
EnhancedFieldTextContainer.propTypes = propTypes;
var _default = EnhancedFieldTextContainer;
exports.default = _default;