'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.readVocabularyItems = exports.READ_VOCABULARY_ITEMS_REJECTED = exports.READ_VOCABULARY_ITEMS_FULFILLED = exports.READ_VOCABULARY_ITEMS_STARTED = undefined;

var _cspace = require('./cspace');

var _cspace2 = _interopRequireDefault(_cspace);

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

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

const READ_VOCABULARY_ITEMS_STARTED = exports.READ_VOCABULARY_ITEMS_STARTED = 'READ_VOCABULARY_ITEMS_STARTED';
const READ_VOCABULARY_ITEMS_FULFILLED = exports.READ_VOCABULARY_ITEMS_FULFILLED = 'READ_VOCABULARY_ITEMS_FULFILLED';
const READ_VOCABULARY_ITEMS_REJECTED = exports.READ_VOCABULARY_ITEMS_REJECTED = 'READ_VOCABULARY_ITEMS_REJECTED';

const readVocabularyItems = exports.readVocabularyItems = vocabularyName => (dispatch, getState) => {
  const vocabulary = (0, _reducers.getVocabulary)(getState(), vocabularyName);

  if (vocabulary && (vocabulary.isReadPending || vocabulary.items)) {
    return Promise.resolve();
  }

  dispatch({
    type: READ_VOCABULARY_ITEMS_STARTED,
    meta: {
      vocabulary: vocabularyName
    }
  });

  const config = {
    params: {
      pgSz: '0',
      wf_deleted: false,
      sortBy: 'vocabularyitems_common:order, vocabularyitems_common:displayName'
    }
  };

  return (0, _cspace2.default)().read(`vocabularies/urn:cspace:name(${vocabularyName})/items`, config).then(response => dispatch({
    type: READ_VOCABULARY_ITEMS_FULFILLED,
    payload: response,
    meta: {
      vocabulary: vocabularyName
    }
  })).catch(error => dispatch({
    type: READ_VOCABULARY_ITEMS_REJECTED,
    payload: error,
    meta: {
      vocabulary: vocabularyName
    }
  }));
};