'use strict';

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

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); // TODO: Break out non-state related props into a separate component. This component should just
// connect to redux state.

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 _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 _workflowStateHelpers = require('../../helpers/workflowStateHelpers');

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

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 filterSource = function filterSource(source, perms) {
  // Filter out sources for which we don't have list permission.

  if (!source) {
    return source;
  }

  var filtered = source.split(',').filter(function (sourceID) {
    return (0, _permissionHelpers.canList)(sourceID.split('/', 1)[0], perms);
  }).join(',');

  return filtered;
};

var filterQuickAddTo = function 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(function (sourceID) {
    var _sourceID$split = sourceID.split('/'),
        _sourceID$split2 = _slicedToArray(_sourceID$split, 2),
        recordType = _sourceID$split2[0],
        vocabulary = _sourceID$split2[1];

    return (0, _permissionHelpers.canCreate)(recordType, perms) && !(0, _workflowStateHelpers.isLocked)((0, _reducers.getAuthorityVocabWorkflowState)(state, recordType, vocabulary));
  }).join(',');
};

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


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

var mapDispatchToProps = function mapDispatchToProps(dispatch, ownProps) {
  var config = ownProps.config,
      _onClose = ownProps.onClose;


  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(source, partialTerm) {
      var sources = (0, _parseResourceID2.default)(source);

      sources.forEach(function (sourceSpec) {
        var recordType = sourceSpec.recordType,
            vocabulary = sourceSpec.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)());

      if (_onClose) {
        _onClose();
      }
    }
  };
};

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;