"use strict";

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

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

const normalizeItems = items => items && !Array.isArray(items) ? [items] : items;

const clearAll = () => ({});

const handleLoginFulfilled = (state, action) => {
  const {
    prevUsername,
    username
  } = action.meta;

  if (prevUsername !== username) {
    // The logged in user has changed. Remove all vocabulary state, because the new user may not be
    // permitted to read vocabularies.
    return clearAll(state);
  }

  return state;
};

const handleRecordSaveFulfilled = (state, action) => {
  const {
    recordTypeConfig
  } = action.meta;

  if (recordTypeConfig.name === 'vocabulary') {
    return clearAll(state);
  }

  return state;
};

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

  switch (action.type) {
    case _actionCodes.READ_VOCABULARY_ITEMS_STARTED:
      return Object.assign({}, state, {
        [action.meta.vocabulary]: {
          isReadPending: true,
          items: null
        }
      });

    case _actionCodes.READ_VOCABULARY_ITEMS_FULFILLED:
      return Object.assign({}, state, {
        [action.meta.vocabulary]: {
          items: normalizeItems(action.payload.data['ns2:abstract-common-list']['list-item'])
        }
      });

    case _actionCodes.READ_VOCABULARY_ITEMS_REJECTED:
      return Object.assign({}, state, {
        [action.meta.vocabulary]: {
          error: action.payload
        }
      });

    case _actionCodes.RECORD_SAVE_FULFILLED:
      return handleRecordSaveFulfilled(state, action);

    case _actionCodes.LOGIN_FULFILLED:
      return handleLoginFulfilled(state, action);

    case _actionCodes.LOGOUT_FULFILLED:
      return clearAll(state);

    default:
      return state;
  }
};

exports.default = _default;

function get(state, vocabularyName) {
  return state[vocabularyName];
}