'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 }; }

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

var resetLogin = exports.resetLogin = function resetLogin(username) {
  return {
    type: RESET_LOGIN,
    meta: {
      username: username
    }
  };
};

var renewAuth = function renewAuth(config, username, password) {
  return function (dispatch) {
    var session = (0, _cspace.createSession)(username, password);

    return session.login().then(function () {
      return session.read('accounts/0/accountperms');
    }).then(function (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(function () {
          return Promise.reject({
            code: _errorCodes.ERR_WRONG_TENANT
          });
        }).catch(function () {
          return Promise.reject({
            code: _errorCodes.ERR_WRONG_TENANT
          });
        });
      }

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

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


      if (!code) {
        var 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: code,
          error: error
        },
        meta: {
          username: username
        }
      });

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

var login = exports.login = function login(config, username, password) {
  return function (dispatch, getState) {
    var prevUsername = (0, _reducers.getUserUsername)(getState());

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

    dispatch({
      type: LOGIN_STARTED,
      meta: {
        username: username
      }
    });

    return dispatch(renewAuth(config, username, password)).then(function () {
      return dispatch((0, _prefs.loadPrefs)(username));
    }).then(function () {
      return dispatch((0, _authority.readAuthVocabs)());
    }).then(function () {
      return dispatch({
        type: LOGIN_FULFILLED,
        meta: {
          prevUsername: prevUsername,
          username: username
        }
      });
    }).catch(function (error) {
      return dispatch({
        type: LOGIN_REJECTED,
        payload: error,
        meta: {
          username: username
        }
      });
    });
  };
};