"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.readAuthVocabs = exports.checkForUses = void 0;
var _get = _interopRequireDefault(require("lodash/get"));
var _session = _interopRequireDefault(require("../helpers/session"));
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, _session.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, and
    // 404 Not Found might happen if an authority isn't configured/available in the services
    // layer. Just swallow these, but reject other errors.

    const status = (0, _get.default)(error, ['response', 'status']);
    return status === 403 || status === 404 ? 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, _session.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;