'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getRoles = exports.isRolesReadPending = exports.getResourceNames = exports.isPermsReadPending = undefined;

var _immutable = require('immutable');

var _immutable2 = _interopRequireDefault(_immutable);

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

var _get2 = _interopRequireDefault(_get);

var _configHelpers = require('../helpers/configHelpers');

var _authz = require('../actions/authz');

var _record = require('../actions/record');

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

const handlePermsReadFulfilled = (state, action) => {
  const config = action.meta.config;


  let perms = (0, _get2.default)(action.payload.data, ['ns2:permissions_list', 'permission']);

  if (perms && !Array.isArray(perms)) {
    perms = [perms];
  }

  const resourceNames = perms.filter(perm => (0, _configHelpers.getRecordTypeConfigByServicePath)(config, perm.resourceName)).map(perm => perm.resourceName);

  return state.set('resourceNames', _immutable2.default.List(resourceNames)).delete('isPermsReadPending');
};

const handleRolesReadFulfilled = (state, action) => {
  let roles = (0, _get2.default)(action.payload.data, ['ns2:roles_list', 'role']);

  if (roles && !Array.isArray(roles)) {
    roles = [roles];
  }

  return state.set('roles', _immutable2.default.fromJS(roles)).delete('isRolesReadPending');
};

const handleRecordCreated = (state, action) => {
  if (action.meta.recordTypeConfig.name === 'authrole') {
    return state.delete('roles');
  }

  return state;
};

const handleRecordDeleteFulfilled = (state, action) => {
  if (action.meta.recordTypeConfig.name === 'authrole') {
    return state.delete('roles');
  }

  return state;
};

exports.default = (state = _immutable2.default.Map(), action) => {
  switch (action.type) {
    case _authz.PERMS_READ_STARTED:
      return state.set('isPermsReadPending', true);
    case _authz.PERMS_READ_FULFILLED:
      return handlePermsReadFulfilled(state, action);
    case _authz.PERMS_READ_REJECTED:
      return state.delete('isPermsReadPending');
    case _authz.ROLES_READ_STARTED:
      return state.set('isRolesReadPending', true);
    case _authz.ROLES_READ_FULFILLED:
      return handleRolesReadFulfilled(state, action);
    case _authz.ROLES_READ_REJECTED:
      return state.delete('isRolesReadPending');
    case _record.RECORD_CREATED:
      return handleRecordCreated(state, action);
    case _record.RECORD_DELETE_FULFILLED:
      return handleRecordDeleteFulfilled(state, action);
    default:
      return state;
  }
};

const isPermsReadPending = exports.isPermsReadPending = state => state.get('isPermsReadPending');
const getResourceNames = exports.getResourceNames = state => state.get('resourceNames');

const isRolesReadPending = exports.isRolesReadPending = state => state.get('isRolesReadPending');
const getRoles = exports.getRoles = state => state.get('roles');