"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.configureCSpace = exports.readSystemInfo = exports.setSession = exports.createSession = void 0;

var _cspaceClient = _interopRequireDefault(require("cspace-client"));

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

var _modalNames = require("../constants/modalNames");

var _session = _interopRequireWildcard(require("../helpers/session"));

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

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

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

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

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

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

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

let client;

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

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

exports.createSession = createSession;

const setSession = newSession => {
  (0, _session.storeSession)(newSession);
  return {
    type: _actionCodes.CSPACE_CONFIGURED,
    payload: (0, _session.default)().config()
  };
};

exports.setSession = setSession;

const readSystemInfo = config => dispatch => (0, _session.default)().read('systeminfo', {
  auth: false,
  params: {
    tid: (0, _get.default)(config, 'tenantId')
  }
}).then(response => dispatch({
  type: _actionCodes.SYSTEM_INFO_READ_FULFILLED,
  payload: response
})).catch(error => dispatch({
  type: _actionCodes.SYSTEM_INFO_READ_REJECTED,
  payload: error
}));

exports.readSystemInfo = readSystemInfo;

const configureCSpace = config => dispatch => {
  client = (0, _cspaceClient.default)({
    url: (0, _get.default)(config, 'serverUrl'),
    onError: error => {
      const status = (0, _get.default)(error, ['response', 'status']);

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

        if (internalError === 'invalid_token') {
          // The stored token is no longer valid. Show the login modal.
          dispatch({
            type: _actionCodes.RESET_LOGIN,
            meta: {
              username: (0, _session.default)().config().username
            }
          });
          dispatch((0, _notification.openModal)(_modalNames.MODAL_LOGIN));
        }
      }

      return Promise.reject(error);
    }
  });
  const newSession = createSession();
  dispatch(setSession(newSession));
  const {
    username
  } = newSession.config();

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

  return dispatch((0, _account.readAccountPerms)(config)).then(() => dispatch((0, _account.readAccountRoles)(config, username))).then(() => dispatch((0, _prefs.loadPrefs)(config, 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, _get.default)(error, ['response', 'status']);

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

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

exports.configureCSpace = configureCSpace;