"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.ConnectedAutocompleteInput = void 0;
var _propTypes = _interopRequireDefault(require("prop-types"));
var _reactRedux = require("react-redux");
var _reactIntl = require("react-intl");
var _get = _interopRequireDefault(require("lodash/get"));
var _cspaceInput = require("cspace-input");
var _warning = _interopRequireDefault(require("warning"));
var _permissionHelpers = require("../../helpers/permissionHelpers");
var _parseResourceID = _interopRequireDefault(require("../../helpers/parseResourceID"));
var _workflowStateHelpers = require("../../helpers/workflowStateHelpers");
var _partialTermSearch = require("../../actions/partialTermSearch");
var _withConfig = _interopRequireDefault(require("../../enhancers/withConfig"));
var _reducers = require("../../reducers");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// TODO: Break out non-state related props into a separate component. This component should just
// connect to redux state.

const {
  AutocompleteInput
} = _cspaceInput.components;
const messages = (0, _reactIntl.defineMessages)({
  count: {
    "id": "autocompleteInputContainer.count",
    "defaultMessage": "{count, plural, =0 {No matching terms} one {# matching term} other {# matching terms}} found"
  },
  moreCharsRequired: {
    "id": "autocompleteInputContainer.moreCharsRequired",
    "defaultMessage": "Continue typing to find matching terms"
  },
  addPrompt: {
    "id": "autocompleteInputContainer.addPrompt",
    "defaultMessage": "Add \"{displayName}\" to {destinationName}"
  },
  cloneOptionLabel: {
    "id": "autocompleteInputContainer.cloneOptionLabel",
    "defaultMessage": "Clone current record"
  },
  createNewOptionLabel: {
    "id": "autocompleteInputContainer.createNewOptionLabel",
    "defaultMessage": "Create new record"
  }
});
const filterSource = (source, perms) => {
  // Filter out sources for which we don't have list permission.

  if (!source) {
    return source;
  }
  const filtered = source.split(',').filter(sourceID => (0, _permissionHelpers.canList)(sourceID.split('/', 1)[0], perms)).join(',');
  return filtered;
};
const filterQuickAddTo = (source, perms, state) => {
  // Filter out sources for which we don't have create permission, or are locked.

  if (!source) {
    return source;
  }
  return source.split(',').filter(sourceID => {
    const [recordType, vocabulary] = sourceID.split('/');
    return (0, _permissionHelpers.canCreate)(recordType, perms) && !(0, _workflowStateHelpers.isLocked)((0, _reducers.getAuthorityVocabWorkflowState)(state, recordType, vocabulary));
  }).join(',');
};
const mapStateToProps = (state, ownProps) => {
  const {
    intl,
    config,
    source
  } = ownProps;
  const perms = (0, _reducers.getUserPerms)(state);
  return {
    findDelay: config.autocompleteFindDelay,
    minLength: config.autocompleteMinLength,
    matches: (0, _reducers.getPartialTermSearchMatches)(state),
    recordTypes: config.recordTypes,
    source: filterSource(source, perms),
    quickAddTo: filterQuickAddTo(source, perms, state),
    formatAddPrompt: function (displayName) {
      let destinationName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
      return intl.formatMessage(messages.addPrompt, {
        displayName,
        destinationName
      });
    },
    formatCloneOptionLabel: () => intl.formatMessage(messages.cloneOptionLabel),
    formatCreateNewOptionLabel: () => intl.formatMessage(messages.createNewOptionLabel),
    formatMoreCharsRequiredMessage: () => intl.formatMessage(messages.moreCharsRequired),
    formatSearchResultMessage: count => intl.formatMessage(messages.count, {
      count
    }),
    formatSourceName: (recordTypeConfig, vocabulary) => intl.formatMessage(vocabulary ? (0, _get.default)(recordTypeConfig, ['vocabularies', vocabulary, 'messages', 'collectionName']) : (0, _get.default)(recordTypeConfig, ['messages', 'record', 'collectionName']))
  };
};
const mapDispatchToProps = (dispatch, ownProps) => {
  const {
    config,
    onClose
  } = ownProps;
  return {
    addTerm: (recordType, vocabulary, displayName, partialTerm, clone) => {
      const recordTypeConfig = (0, _get.default)(config, ['recordTypes', recordType]);
      process.env.NODE_ENV !== "production" ? (0, _warning.default)(recordTypeConfig, `The record type '${recordType}' is not configured. Check the source prop of the input with name '${ownProps.name}'.`) : void 0;
      if (recordTypeConfig) {
        dispatch((0, _partialTermSearch.addTerm)(recordTypeConfig, vocabulary, displayName, partialTerm, clone));
      }
    },
    findMatchingTerms: (source, partialTerm) => {
      const sources = (0, _parseResourceID.default)(source);
      sources.forEach(sourceSpec => {
        const {
          recordType,
          vocabulary
        } = sourceSpec;
        const recordTypeConfig = config.recordTypes[recordType];
        process.env.NODE_ENV !== "production" ? (0, _warning.default)(recordTypeConfig, `The record type '${recordType}' is not configured. Check the source prop of the input with name '${ownProps.name}'.`) : void 0;
        if (recordTypeConfig) {
          dispatch((0, _partialTermSearch.findMatchingTerms)(recordTypeConfig, vocabulary, partialTerm));
        }
      });
    },
    onClose: () => {
      dispatch((0, _partialTermSearch.clearMatchedTerms)());
      if (onClose) {
        onClose();
      }
    }
  };
};
const mergeProps = (stateProps, dispatchProps, ownProps) => {
  const {
    intl,
    config,
    ...remainingOwnProps
  } = ownProps;
  return {
    ...remainingOwnProps,
    ...stateProps,
    ...dispatchProps
  };
};
const ConnectedAutocompleteInput = (0, _reactRedux.connect)(mapStateToProps, mapDispatchToProps, mergeProps)(AutocompleteInput);
exports.ConnectedAutocompleteInput = ConnectedAutocompleteInput;
const IntlizedConnectedAutocompleteInput = (0, _reactIntl.injectIntl)((0, _withConfig.default)(ConnectedAutocompleteInput));
IntlizedConnectedAutocompleteInput.propTypes = {
  ...AutocompleteInput.propTypes,
  source: _propTypes.default.string.isRequired,
  // eslint-disable-next-line react/forbid-prop-types
  config: _propTypes.default.object
};
var _default = IntlizedConnectedAutocompleteInput;
exports.default = _default;