"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.arePrefsLoaded = exports.getPerms = exports.getUserId = exports.getScreenName = exports.getUsername = exports.default = void 0;

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

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

var _permissionHelpers = require("../helpers/permissionHelpers");

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

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

const handleAccountPermsReadFulfilled = (state, action) => {
  const {
    config
  } = action.meta;
  const {
    data
  } = action.payload;

  const account = _immutable.default.fromJS((0, _get.default)(data, ['ns2:account_permission', 'account']));

  const accountTenantId = account.get('tenantId');
  const perms = accountTenantId === config.tenantId ? (0, _permissionHelpers.getPermissions)(action.meta.config, data) : _immutable.default.Map();
  return state.set('account', account).set('perms', perms);
};

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.ACCOUNT_PERMS_READ_FULFILLED:
      return handleAccountPermsReadFulfilled(state, action);

    case _actionCodes.AUTH_RENEW_FULFILLED:
      return handleAccountPermsReadFulfilled(state, action);

    case _actionCodes.CSPACE_CONFIGURED:
      return state.set('username', action.payload.username);

    case _actionCodes.LOGIN_FULFILLED:
      return state.set('username', action.meta.username);

    case _actionCodes.LOGOUT_FULFILLED:
      return state.clear();

    case _actionCodes.SET_ACCOUNT_PERMS:
      // There is no action creator that creates this action, but it's useful for testing via Redux
      // dev tools.
      return state.set('perms', state.get('perms').mergeDeep(_immutable.default.fromJS(action.payload)));

    case _actionCodes.PREFS_LOADED:
      return state.set('prefsLoaded', true);

    default:
      return state;
  }
};

exports.default = _default;

const getUsername = state => state.get('username');

exports.getUsername = getUsername;

const getScreenName = state => state.getIn(['account', 'screenName']);

exports.getScreenName = getScreenName;

const getUserId = state => state.getIn(['account', 'userId']);

exports.getUserId = getUserId;

const getPerms = state => state.get('perms');

exports.getPerms = getPerms;

const arePrefsLoaded = state => state.get('prefsLoaded') === true;

exports.arePrefsLoaded = arePrefsLoaded;