"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.resetPassword = exports.requestPasswordReset = exports.readAccountRoles = exports.readAccountPerms = exports.checkForRoleUses = void 0;

var _get = _interopRequireDefault(require("lodash/get"));

var _session = _interopRequireDefault(require("../helpers/session"));

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

var _actionCodes = require("../constants/actionCodes");

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

/* global btoa */
const checkForRoleUses = csid => () => (0, _session.default)().read(`authorization/roles/${csid}/accountroles`).then(response => {
  const account = (0, _get.default)(response, ['data', 'ns2:account_role', 'account']);
  return !!account;
});

exports.checkForRoleUses = checkForRoleUses;

const readAccountPerms = config => dispatch => (0, _session.default)().read('accounts/0/accountperms').then(response => dispatch({
  type: _actionCodes.ACCOUNT_PERMS_READ_FULFILLED,
  payload: response,
  meta: {
    config
  }
})).catch(error => {
  dispatch({
    type: _actionCodes.ACCOUNT_PERMS_READ_REJECTED,
    payload: error
  });
  return Promise.reject(error);
});

exports.readAccountPerms = readAccountPerms;

const readAccountRoles = () => (dispatch, getState) => {
  const accountId = (0, _reducers.getUserAccountId)(getState());
  return (0, _session.default)().read(`accounts/${accountId}/accountroles`).then(response => dispatch({
    type: _actionCodes.ACCOUNT_ROLES_READ_FULFILLED,
    payload: response
  })).catch(error => {
    dispatch({
      type: _actionCodes.ACCOUNT_ROLES_READ_REJECTED,
      payload: error
    });
    return Promise.reject(error);
  });
};

exports.readAccountRoles = readAccountRoles;

const requestPasswordReset = (email, tenantId) => () => {
  const config = {
    params: {
      email,
      tid: tenantId
    }
  };
  return (0, _session.default)().create('accounts/requestpasswordreset', config);
};

exports.requestPasswordReset = requestPasswordReset;

const resetPassword = (password, token) => () => {
  const config = {
    data: {
      'ns2:passwordreset': {
        '@xmlns:ns2': 'http://collectionspace.org/services/authentication',
        token,
        password: btoa(password)
      }
    }
  };
  return (0, _session.default)().create('accounts/processpasswordreset', config);
};

exports.resetPassword = resetPassword;
var _default = {};
exports.default = _default;