'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.readRoles = exports.readPerms = exports.ROLES_READ_REJECTED = exports.ROLES_READ_FULFILLED = exports.ROLES_READ_STARTED = exports.PERMS_READ_REJECTED = exports.PERMS_READ_FULFILLED = exports.PERMS_READ_STARTED = undefined;

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

var _cspace2 = _interopRequireDefault(_cspace);

var _errorCodes = require('../constants/errorCodes');

var _reducers = require('../reducers');

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

const PERMS_READ_STARTED = exports.PERMS_READ_STARTED = 'PERMS_READ_STARTED';
const PERMS_READ_FULFILLED = exports.PERMS_READ_FULFILLED = 'PERMS_READ_FULFILLED';
const PERMS_READ_REJECTED = exports.PERMS_READ_REJECTED = 'PERMS_READ_REJECTED';
const ROLES_READ_STARTED = exports.ROLES_READ_STARTED = 'ROLES_READ_STARTED';
const ROLES_READ_FULFILLED = exports.ROLES_READ_FULFILLED = 'ROLES_READ_FULFILLED';
const ROLES_READ_REJECTED = exports.ROLES_READ_REJECTED = 'ROLES_READ_REJECTED';

const readPerms = exports.readPerms = config => (dispatch, getState) => {
  if ((0, _reducers.isAuthzPermsReadPending)(getState()) || (0, _reducers.getAuthzResourceNames)(getState())) {
    // We've already read the perms, or a request is already pending. Do nothing.

    return Promise.resolve();
  }

  const requestConfig = {
    params: {
      pgSz: 0,
      actGrp: 'CRUDL'
    }
  };

  dispatch({
    type: PERMS_READ_STARTED
  });

  return (0, _cspace2.default)().read('authorization/permissions', requestConfig).then(response => {
    dispatch({
      type: PERMS_READ_FULFILLED,
      payload: response,
      meta: {
        config
      }
    });
  }).catch(error => {
    dispatch({
      type: PERMS_READ_REJECTED,
      payload: {
        code: _errorCodes.ERR_API,
        error
      }
    });
  });
};

const readRoles = exports.readRoles = () => (dispatch, getState) => {
  if ((0, _reducers.isAuthzRolesReadPending)(getState()) || (0, _reducers.getAuthzRoles)(getState())) {
    // We've already read the perms, or a request is already pending. Do nothing.

    return Promise.resolve();
  }

  const requestConfig = {
    params: {
      pgSz: 0
    }
  };

  dispatch({
    type: ROLES_READ_STARTED
  });

  return (0, _cspace2.default)().read('authorization/roles', requestConfig).then(response => {
    dispatch({
      type: ROLES_READ_FULFILLED,
      payload: response
    });
  }).catch(error => {
    dispatch({
      type: ROLES_READ_REJECTED,
      payload: {
        code: _errorCodes.ERR_API,
        error
      }
    });
  });
};