'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getPerms = exports.getUserId = 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 }; }

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


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

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

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

exports.default = (state = _immutable2.default.Map(), action) => {
  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;
  }
};

const getUsername = exports.getUsername = state => state.get('username');
const getScreenName = exports.getScreenName = state => state.getIn(['account', 'screenName']);
const getUserId = exports.getUserId = state => state.getIn(['account', 'userId']);
const getPerms = exports.getPerms = state => state.get('perms');