"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.readVocabularyItemRefs = exports.readVocabularyItems = void 0;

var _session = _interopRequireDefault(require("../helpers/session"));

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

var _actionCodes = require("../constants/actionCodes");

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

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

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

  dispatch({
    type: _actionCodes.READ_VOCABULARY_ITEMS_STARTED,
    meta: {
      vocabulary: vocabularyName
    }
  });
  const config = {
    params: {
      pgSz: '0',
      wf_deleted: false,
      sortBy: 'vocabularyitems_common:order, vocabularyitems_common:displayName'
    }
  };
  return (0, _session.default)().read(`vocabularies/urn:cspace:name(${vocabularyName})/items`, config).then(response => dispatch({
    type: _actionCodes.READ_VOCABULARY_ITEMS_FULFILLED,
    payload: response,
    meta: {
      vocabulary: vocabularyName
    }
  })).catch(error => dispatch({
    type: _actionCodes.READ_VOCABULARY_ITEMS_REJECTED,
    payload: error,
    meta: {
      vocabulary: vocabularyName
    }
  }));
};

exports.readVocabularyItems = readVocabularyItems;

const readVocabularyItemRefs = (csid, vocabularyName) => (dispatch, getState) => {
  if ((0, _reducers.isRecordReadVocabularyItemRefsPending)(getState(), csid)) {
    return Promise.resolve();
  }

  dispatch({
    type: _actionCodes.READ_VOCABULARY_ITEM_REFS_STARTED,
    meta: {
      csid,
      vocabulary: vocabularyName
    }
  });
  const config = {
    params: {
      pgSz: '0',
      wf_deleted: false,
      markIfReferenced: true
    }
  };
  return (0, _session.default)().read(`vocabularies/urn:cspace:name(${vocabularyName})/items`, config).then(response => dispatch({
    type: _actionCodes.READ_VOCABULARY_ITEM_REFS_FULFILLED,
    payload: response,
    meta: {
      csid,
      vocabulary: vocabularyName
    }
  })).catch(error => dispatch({
    type: _actionCodes.READ_VOCABULARY_ITEM_REFS_REJECTED,
    payload: error,
    meta: {
      csid,
      vocabulary: vocabularyName
    }
  }));
};

exports.readVocabularyItemRefs = readVocabularyItemRefs;