'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.readAuthVocabs = exports.SET_AUTH_VOCAB_WORKFLOW_STATE = exports.AUTH_VOCABS_READ_REJECTED = exports.AUTH_VOCABS_READ_FULFILLED = exports.AUTH_VOCABS_READ_STARTED = undefined;

var _get = require('lodash/get');

var _get2 = _interopRequireDefault(_get);

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

var _cspace2 = _interopRequireDefault(_cspace);

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

var AUTH_VOCABS_READ_STARTED = exports.AUTH_VOCABS_READ_STARTED = 'AUTH_VOCABS_READ_STARTED';
var AUTH_VOCABS_READ_FULFILLED = exports.AUTH_VOCABS_READ_FULFILLED = 'AUTH_VOCABS_READ_FULFILLED';
var AUTH_VOCABS_READ_REJECTED = exports.AUTH_VOCABS_READ_REJECTED = 'AUTH_VOCABS_READ_REJECTED';
var SET_AUTH_VOCAB_WORKFLOW_STATE = exports.SET_AUTH_VOCAB_WORKFLOW_STATE = 'SET_AUTH_VOCAB_WORKFLOW_STATE';

var readAuthVocabs = exports.readAuthVocabs = function readAuthVocabs(config) {
  return function (dispatch) {
    var recordTypes = (0, _get2.default)(config, 'recordTypes');

    if (!recordTypes) {
      // This is mostly to allow tests to run without having a config.

      return Promise.resolve();
    }

    dispatch({
      type: AUTH_VOCABS_READ_STARTED
    });

    var session = (0, _cspace2.default)();

    var readPromises = Object.values(config.recordTypes).filter(function (recordTypeConfig) {
      return recordTypeConfig.serviceConfig.serviceType === 'authority';
    }).map(function (recordTypeConfig) {
      return session.read(recordTypeConfig.serviceConfig.servicePath);
    });

    return Promise.all(readPromises).then(function (responses) {
      return dispatch({
        type: AUTH_VOCABS_READ_FULFILLED,
        payload: responses,
        meta: {
          config: config
        }
      });
    }).catch(function (error) {
      dispatch({
        type: AUTH_VOCABS_READ_REJECTED,
        payload: error
      });

      return Promise.reject(error);
    });
  };
};