'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.resetPassword = exports.requestPasswordReset = exports.readAccountPerms = exports.checkForRoleUses = exports.SET_ACCOUNT_PERMS = exports.ACCOUNT_PERMS_READ_REJECTED = exports.ACCOUNT_PERMS_READ_FULFILLED = undefined;

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

var _get2 = _interopRequireDefault(_get);

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

var _cspace2 = _interopRequireDefault(_cspace);

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

/* global btoa */

const ACCOUNT_PERMS_READ_FULFILLED = exports.ACCOUNT_PERMS_READ_FULFILLED = 'ACCOUNT_PERMS_READ_FULFILLED';
const ACCOUNT_PERMS_READ_REJECTED = exports.ACCOUNT_PERMS_READ_REJECTED = 'ACCOUNT_PERMS_READ_REJECTED';
const SET_ACCOUNT_PERMS = exports.SET_ACCOUNT_PERMS = 'SET_ACCOUNT_PERMS';

const checkForRoleUses = exports.checkForRoleUses = csid => () => (0, _cspace2.default)().read(`authorization/roles/${csid}/accountroles`).then(response => {
  const account = (0, _get2.default)(response, ['data', 'ns2:account_role', 'account']);

  return !!account;
});

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

  return Promise.reject(error);
});

const requestPasswordReset = exports.requestPasswordReset = (email, tenantId) => () => {
  const config = {
    params: {
      email,
      tid: tenantId
    }
  };

  return (0, _cspace2.default)().create('accounts/requestpasswordreset', config);
};

const resetPassword = exports.resetPassword = (password, token) => () => {
  const config = {
    data: {
      'ns2:passwordreset': {
        '@xmlns:ns2': 'http://collectionspace.org/services/authentication',
        token,
        password: btoa(password)
      }
    }
  };

  return (0, _cspace2.default)().create('accounts/processpasswordreset', config);
};

exports.default = {};