'use strict';

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

var _immutable = require('immutable');

var _immutable2 = _interopRequireDefault(_immutable);

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

var _get2 = _interopRequireDefault(_get);

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

var _authority = require('../actions/authority');

var _logout = require('../actions/logout');

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

var handleAuthVocabsReadFulfilled = function handleAuthVocabsReadFulfilled(state, action) {
  var responses = action.payload;
  var config = action.meta.config;


  var nextState = _immutable2.default.Map();

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

    if (!items) {
      return;
    }

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

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

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

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

  return nextState;
};

var clearAll = function clearAll(state) {
  return state.clear();
};

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

  switch (action.type) {
    case _authority.AUTH_VOCABS_READ_FULFILLED:
      return handleAuthVocabsReadFulfilled(state, action);
    case _logout.LOGOUT_FULFILLED:
      return clearAll(state);
    case _authority.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;
  }
};

var getVocabCsid = exports.getVocabCsid = function getVocabCsid(state, recordType, vocabulary) {
  return state.getIn([recordType, vocabulary, 'csid']);
};

var getVocabWorkflowState = exports.getVocabWorkflowState = function getVocabWorkflowState(state, recordType, vocabulary) {
  return state.getIn([recordType, vocabulary, 'workflowState']);
};