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

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

var readPerms = exports.readPerms = function readPerms(config) {
  return function (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();
    }

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

    dispatch({
      type: PERMS_READ_STARTED
    });

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

var readRoles = exports.readRoles = function readRoles() {
  return function (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();
    }

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

    dispatch({
      type: ROLES_READ_STARTED
    });

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