'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getPerms = exports.getScreenName = exports.getUsername = undefined;

var _immutable = require('immutable');

var _immutable2 = _interopRequireDefault(_immutable);

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

var _get2 = _interopRequireDefault(_get);

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

var _account = require('../actions/account');

var _cspace = require('../actions/cspace');

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

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

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

var handleAccountPermsReadFulfilled = function handleAccountPermsReadFulfilled(state, action) {
  var config = action.meta.config;
  var data = action.payload.data;


  var account = _immutable2.default.fromJS((0, _get2.default)(data, ['ns2:account_permission', 'account']));
  var accountTenantId = account.get('tenantId');

  var perms = accountTenantId === config.tenantId ? (0, _permissionHelpers.getPermissions)(action.meta.config, data) : _immutable2.default.Map();

  return state.set('account', account).set('perms', perms);
};

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

  switch (action.type) {
    case _account.ACCOUNT_PERMS_READ_FULFILLED:
      return handleAccountPermsReadFulfilled(state, action);
    case _login.AUTH_RENEW_FULFILLED:
      return handleAccountPermsReadFulfilled(state, action);
    case _cspace.CSPACE_CONFIGURED:
      return state.set('username', action.payload.username);
    case _login.LOGIN_FULFILLED:
      return state.set('username', action.meta.username);
    case _logout.LOGOUT_FULFILLED:
      return state.clear();
    case _account.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(_immutable2.default.fromJS(action.payload)));
    default:
      return state;
  }
};

var getUsername = exports.getUsername = function getUsername(state) {
  return state.get('username');
};
var getScreenName = exports.getScreenName = function getScreenName(state) {
  return state.getIn(['account', 'screenName']);
};
var getPerms = exports.getPerms = function getPerms(state) {
  return state.get('perms');
};