'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.configureCSpace = exports.setSession = exports.createSession = exports.CSPACE_CONFIGURED = undefined;

var _cspaceClient = require('cspace-client');

var _cspaceClient2 = _interopRequireDefault(_cspaceClient);

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

var _get2 = _interopRequireDefault(_get);

var _login = require('./login');

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

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

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

var _notification = require('./notification');

var _LoginModal = require('../components/login/LoginModal');

var _LoginModal2 = _interopRequireDefault(_LoginModal);

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

const CSPACE_CONFIGURED = exports.CSPACE_CONFIGURED = 'CSPACE_CONFIGURED';

let client;
let session;

const createSession = exports.createSession = (username, password) => {
  if (typeof username === 'undefined' && typeof password === 'undefined') {
    return client.session();
  }

  return client.session({
    username,
    password
  });
};

const setSession = exports.setSession = newSession => {
  session = newSession;

  return {
    type: CSPACE_CONFIGURED,
    payload: session.config()
  };
};

const configureCSpace = exports.configureCSpace = config => dispatch => {
  client = (0, _cspaceClient2.default)({
    url: (0, _get2.default)(config, 'serverUrl'),

    onError: error => {
      const status = (0, _get2.default)(error, ['response', 'status']);

      if (status === 401) {
        const internalError = (0, _get2.default)(error, ['response', 'data', 'error']);

        if (internalError === 'invalid_token') {
          // The stored token is no longer valid. Show the login modal.

          dispatch((0, _login.resetLogin)(session.config().username));
          dispatch((0, _notification.openModal)(_LoginModal2.default.modalName));
        }
      }

      return Promise.reject(error);
    }
  });

  const newSession = createSession();

  dispatch(setSession(newSession));

  var _newSession$config = newSession.config();

  const username = _newSession$config.username;


  if (!username) {
    return Promise.resolve();
  }

  return dispatch((0, _account.readAccountPerms)(config, username)).then(() => dispatch((0, _prefs.loadPrefs)(username))).then(() => dispatch((0, _authority.readAuthVocabs)(config))).catch(error => {
    // 401 is expected if the user's auth token has expired. The client onError handler will take
    // care of showing a notification, so the error can be swallowed here.

    const status = (0, _get2.default)(error, ['response', 'status']);

    if (status === 401) {
      return Promise.resolve();
    }

    return Promise.reject(error);
  });
};

exports.default = () => session;