'use strict';

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

var _login = require('../actions/login');

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

var _vocabulary = require('../actions/vocabulary');

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

const handleLoginFulfilled = (state, action) => {
  var _action$meta = action.meta;
  const prevUsername = _action$meta.prevUsername,
        username = _action$meta.username;


  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;
};

exports.default = (state = {}, action) => {
  switch (action.type) {
    case _vocabulary.READ_VOCABULARY_ITEMS_STARTED:
      return Object.assign({}, state, {
        [action.meta.vocabulary]: {
          isReadPending: true,
          items: null
        }
      });
    case _vocabulary.READ_VOCABULARY_ITEMS_FULFILLED:
      return Object.assign({}, state, {
        [action.meta.vocabulary]: {
          items: action.payload.data['ns2:abstract-common-list']['list-item']
        }
      });
    case _vocabulary.READ_VOCABULARY_ITEMS_REJECTED:
      return Object.assign({}, state, {
        [action.meta.vocabulary]: {
          error: action.payload
        }
      });
    case _login.LOGIN_FULFILLED:
      return handleLoginFulfilled(state, action);
    case _logout.LOGOUT_FULFILLED:
      return clearAll(state);
    default:
      return state;
  }
};

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