"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.login = exports.resetLogin = void 0;

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

var _authority = require("./authority");

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

var _prefs = require("./prefs");

var _account = require("./account");

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

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

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

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

const resetLogin = username => ({
  type: _actionCodes.RESET_LOGIN,
  meta: {
    username
  }
});

exports.resetLogin = resetLogin;

const renewAuth = (config, username, password) => dispatch => {
  const session = (0, _cspace.createSession)(username, password);
  return session.login().then(() => session.read('accounts/0/accountperms')).then(response => {
    if ((0, _get.default)(response, ['data', 'ns2:account_permission', 'account', 'tenantId']) !== config.tenantId) {
      // The logged in user doesn't belong to the tenant that this UI expects.
      return session.logout() // TODO: Use .finally when it's supported in all browsers.
      .then(() => {
        const error = new Error();
        error.code = _errorCodes.ERR_WRONG_TENANT;
        return Promise.reject(error);
      }).catch(() => {
        const error = new Error();
        error.code = _errorCodes.ERR_WRONG_TENANT;
        return Promise.reject(error);
      });
    }

    dispatch((0, _cspace.setSession)(session));
    return dispatch({
      type: _actionCodes.AUTH_RENEW_FULFILLED,
      payload: response,
      meta: {
        config,
        username
      }
    });
  }).then(() => dispatch((0, _account.readAccountRoles)(config, username))).catch(error => {
    let {
      code
    } = error;

    if (!code) {
      const desc = (0, _get.default)(error, ['response', 'data', 'error_description']) || (0, _get.default)(error, 'message');

      if (desc === 'Bad credentials') {
        code = _errorCodes.ERR_INVALID_CREDENTIALS;
      } else if (desc === 'Network Error') {
        code = _errorCodes.ERR_NETWORK;
      }
    }

    dispatch({
      type: _actionCodes.AUTH_RENEW_REJECTED,
      payload: {
        code,
        error
      },
      meta: {
        username
      }
    });
    const wrapper = new Error();
    wrapper.code = code;
    wrapper.error = error;
    return Promise.reject(wrapper);
  });
};

const login = (config, username, password) => (dispatch, getState) => {
  const prevUsername = (0, _reducers.getUserUsername)(getState());
  dispatch((0, _prefs.savePrefs)());
  dispatch({
    type: _actionCodes.LOGIN_STARTED,
    meta: {
      username
    }
  });
  return dispatch(renewAuth(config, username, password)).then(() => dispatch((0, _prefs.loadPrefs)(config, username))).then(() => dispatch((0, _authority.readAuthVocabs)(config))).then(() => dispatch({
    type: _actionCodes.LOGIN_FULFILLED,
    meta: {
      prevUsername,
      username
    }
  })).catch(error => dispatch({
    type: _actionCodes.LOGIN_REJECTED,
    payload: error,
    meta: {
      username
    }
  }));
};

exports.login = login;