'use strict';

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

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

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactRedux = require('react-redux');

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

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

var _get2 = _interopRequireDefault(_get);

var _pickBy = require('lodash/pickBy');

var _pickBy2 = _interopRequireDefault(_pickBy);

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

var _warning = require('warning');

var _warning2 = _interopRequireDefault(_warning);

var _permissionHelpers = require('../../helpers/permissionHelpers');

var _parseResourceID = require('../../helpers/parseResourceID');

var _parseResourceID2 = _interopRequireDefault(_parseResourceID);

var _partialTermSearch = require('../../actions/partialTermSearch');

var _withConfig = require('../../enhancers/withConfig');

var _withConfig2 = _interopRequireDefault(_withConfig);

var _reducers = require('../../reducers');

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

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } // TODO: Break out non-state related props into a separate component. This component should just
// connect to redux state.

var AutocompleteInput = _cspaceInput.components.AutocompleteInput;


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

var getRecordTypes = function getRecordTypes(config, perms) {
  var recordTypes = config.recordTypes;


  return (0, _pickBy2.default)(recordTypes, function (recordTypeConfig, name) {
    var serviceType = (0, _get2.default)(recordTypeConfig, ['serviceConfig', 'serviceType']);

    return (serviceType === 'object' || serviceType === 'procedure' || serviceType === 'authority') && (0, _permissionHelpers.canCreate)(name, perms);
  });
};

var mapStateToProps = function mapStateToProps(state, ownProps) {
  var intl = ownProps.intl,
      config = ownProps.config;


  var perms = (0, _reducers.getUserPerms)(state);

  return {
    formatAddPrompt: function formatAddPrompt(displayName) {
      return intl.formatMessage(messages.addPrompt, { displayName: displayName });
    },
    formatMoreCharsRequiredMessage: function formatMoreCharsRequiredMessage() {
      return intl.formatMessage(messages.moreCharsRequired);
    },
    formatSearchResultMessage: function formatSearchResultMessage(count) {
      return intl.formatMessage(messages.count, { count: count });
    },
    formatSourceName: function formatSourceName(recordTypeConfig, vocabulary) {
      return intl.formatMessage(vocabulary ? (0, _get2.default)(recordTypeConfig, ['vocabularies', vocabulary, 'messages', 'collectionName']) : (0, _get2.default)(recordTypeConfig, ['messages', 'record', 'collectionName']));
    },
    matches: (0, _reducers.getPartialTermSearchMatches)(state),
    recordTypes: getRecordTypes(config, perms)
  };
};

var mapDispatchToProps = function mapDispatchToProps(dispatch, ownProps) {
  var config = ownProps.config,
      sourceID = ownProps.source;


  var sources = (0, _parseResourceID2.default)(sourceID);

  return {
    addTerm: function addTerm(recordType, vocabulary, displayName) {
      var recordTypeConfig = (0, _get2.default)(config, ['recordTypes', recordType]);

      process.env.NODE_ENV !== 'production' ? (0, _warning2.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));
      }
    },
    findMatchingTerms: function findMatchingTerms(partialTerm) {
      sources.forEach(function (source) {
        var recordType = source.recordType,
            vocabulary = source.vocabulary;


        var recordTypeConfig = config.recordTypes[recordType];

        process.env.NODE_ENV !== 'production' ? (0, _warning2.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: function onClose() {
      dispatch((0, _partialTermSearch.clearMatchedTerms)());
    }
  };
};

var mergeProps = function mergeProps(stateProps, dispatchProps, ownProps) {
  var intl = ownProps.intl,
      config = ownProps.config,
      remainingOwnProps = _objectWithoutProperties(ownProps, ['intl', 'config']);

  return Object.assign({}, remainingOwnProps, stateProps, dispatchProps);
};

var ConnectedAutocompleteInput = exports.ConnectedAutocompleteInput = (0, _reactRedux.connect)(mapStateToProps, mapDispatchToProps, mergeProps)(AutocompleteInput);

var IntlizedConnectedAutocompleteInput = (0, _reactIntl.injectIntl)((0, _withConfig2.default)(ConnectedAutocompleteInput));

IntlizedConnectedAutocompleteInput.propTypes = Object.assign({}, AutocompleteInput.propTypes, {
  source: _propTypes2.default.string.isRequired,
  config: _propTypes2.default.object
});

exports.default = IntlizedConnectedAutocompleteInput;