'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.login = exports.resetLogin = exports.LOGIN_REJECTED = exports.LOGIN_FULFILLED = exports.LOGIN_STARTED = exports.RESET_LOGIN = exports.AUTH_RENEW_REJECTED = exports.AUTH_RENEW_FULFILLED = undefined;

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

var _get2 = _interopRequireDefault(_get);

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

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

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

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

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

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

const AUTH_RENEW_FULFILLED = exports.AUTH_RENEW_FULFILLED = 'AUTH_RENEW_FULFILLED';
const AUTH_RENEW_REJECTED = exports.AUTH_RENEW_REJECTED = 'AUTH_RENEW_REJECTED';
const RESET_LOGIN = exports.RESET_LOGIN = 'RESET_LOGIN';
const LOGIN_STARTED = exports.LOGIN_STARTED = 'LOGIN_STARTED';
const LOGIN_FULFILLED = exports.LOGIN_FULFILLED = 'LOGIN_FULFILLED';
const LOGIN_REJECTED = exports.LOGIN_REJECTED = 'LOGIN_REJECTED';

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

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, _get2.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(() => Promise.reject({
        code: _errorCodes.ERR_WRONG_TENANT
      })).catch(() => Promise.reject({
        code: _errorCodes.ERR_WRONG_TENANT
      }));
    }

    dispatch((0, _cspace.setSession)(session));

    return dispatch({
      type: AUTH_RENEW_FULFILLED,
      payload: response,
      meta: {
        config,
        username
      }
    });
  }).catch(error => {
    let code = error.code;


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

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

    dispatch({
      type: AUTH_RENEW_REJECTED,
      payload: {
        code,
        error
      },
      meta: {
        username
      }
    });

    return Promise.reject({
      code,
      error
    });
  });
};

const login = exports.login = (config, username, password) => (dispatch, getState) => {
  const prevUsername = (0, _reducers.getUserUsername)(getState());

  dispatch((0, _prefs.savePrefs)());

  dispatch({
    type: 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: LOGIN_FULFILLED,
    meta: {
      prevUsername,
      username
    }
  })).catch(error => dispatch({
    type: LOGIN_REJECTED,
    payload: error,
    meta: {
      username
    }
  }));
};