"use strict";

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

var _get = _interopRequireDefault(require("lodash/get"));

var _cspace = _interopRequireDefault(require("./cspace"));

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

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

const readAuthVocabs = config => dispatch => {
  const recordTypes = (0, _get.default)(config, 'recordTypes');

  if (!recordTypes) {
    // This is mostly to allow tests to run without having a config.
    return Promise.resolve();
  }

  dispatch({
    type: _actionCodes.AUTH_VOCABS_READ_STARTED
  });
  const session = (0, _cspace.default)();
  const readPromises = Object.values(config.recordTypes).filter(recordTypeConfig => recordTypeConfig.serviceConfig.serviceType === 'authority').map(recordTypeConfig => session.read(recordTypeConfig.serviceConfig.servicePath).catch(error => // 403 Forbidden might happen if the user doesn't have any permissions on an authority.
  // Just swallow this, but reject other errors.
  (0, _get.default)(error, ['response', 'status']) === 403 ? undefined : Promise.reject(error)));
  return Promise.all(readPromises).then(responses => dispatch({
    type: _actionCodes.AUTH_VOCABS_READ_FULFILLED,
    payload: responses,
    meta: {
      config
    }
  })).catch(error => {
    dispatch({
      type: _actionCodes.AUTH_VOCABS_READ_REJECTED,
      payload: error
    });
    return Promise.reject(error);
  });
};
/**
 * Check if any uses exist for the given authority item. Resolves to true or false.
 */


exports.readAuthVocabs = readAuthVocabs;

const checkForUses = (config, recordType, vocabulary, csid) => () => {
  const recordTypeConfig = (0, _get.default)(config, ['recordTypes', recordType]);
  const vocabularyConfig = (0, _get.default)(recordTypeConfig, ['vocabularies', vocabulary]);
  const recordServicePath = (0, _get.default)(recordTypeConfig, ['serviceConfig', 'servicePath']);
  const vocabularyServicePath = (0, _get.default)(vocabularyConfig, ['serviceConfig', 'servicePath']);
  const pathParts = [recordServicePath, vocabularyServicePath, 'items', csid, 'refObjs'];
  const path = pathParts.join('/');
  const requestConfig = {
    params: {
      wf_deleted: 'false',
      pgSz: '1'
    }
  };
  return (0, _cspace.default)().read(path, requestConfig).then(response => {
    const totalItems = (0, _get.default)(response, ['data', 'ns3:authority-ref-doc-list', 'totalItems']);
    return totalItems && parseInt(totalItems, 10) > 0;
  });
};

exports.checkForUses = checkForUses;