"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getVocabWorkflowState = exports.getVocabCsid = exports.default = void 0;

var _immutable = _interopRequireDefault(require("immutable"));

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

var _configHelpers = require("../helpers/configHelpers");

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

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

const handleAuthVocabsReadFulfilled = (state, action) => {
  const responses = action.payload;
  const {
    config
  } = action.meta;

  let nextState = _immutable.default.Map();

  responses.forEach(response => {
    let items = (0, _get.default)(response, ['data', 'ns2:abstract-common-list', 'list-item']);

    if (!items) {
      return;
    }

    if (!Array.isArray(items)) {
      items = [items];
    }

    items.forEach(item => {
      const recordTypeConfig = (0, _configHelpers.getRecordTypeConfigByUri)(config, item.uri);

      if (recordTypeConfig) {
        const vocabularyConfig = (0, _configHelpers.getVocabularyConfigByShortID)(recordTypeConfig, item.shortIdentifier);

        if (vocabularyConfig) {
          nextState = nextState.setIn([recordTypeConfig.name, vocabularyConfig.name], _immutable.default.Map({
            csid: item.csid,
            workflowState: item.workflowState
          }));
        }
      }
    });
  });
  return nextState;
};

const clearAll = state => state.clear();

var _default = function _default() {
  let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _immutable.default.Map();
  let action = arguments.length > 1 ? arguments[1] : undefined;

  switch (action.type) {
    case _actionCodes.AUTH_VOCABS_READ_FULFILLED:
      return handleAuthVocabsReadFulfilled(state, action);

    case _actionCodes.LOGOUT_FULFILLED:
      return clearAll(state);

    case _actionCodes.SET_AUTH_VOCAB_WORKFLOW_STATE:
      // There's no action creator that creates this action, but it's useful for testing via Redux
      // dev tools.
      return state.setIn([action.meta.recordType, action.meta.vocabulary, 'workflowState'], action.payload);

    default:
      return state;
  }
};

exports.default = _default;

const getVocabCsid = (state, recordType, vocabulary) => state.getIn([recordType, vocabulary, 'csid']);

exports.getVocabCsid = getVocabCsid;

const getVocabWorkflowState = (state, recordType, vocabulary) => state.getIn([recordType, vocabulary, 'workflowState']);

exports.getVocabWorkflowState = getVocabWorkflowState;