'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _asyncToGenerator = require('@babel/runtime/helpers/asyncToGenerator');
var _regeneratorRuntime = require('@babel/runtime/regenerator');
require('core-js/modules/es.symbol.js');
require('core-js/modules/es.array.concat.js');
require('core-js/modules/es.array.filter.js');
require('core-js/modules/es.array.find.js');
require('core-js/modules/es.array.find-index.js');
require('core-js/modules/es.array.includes.js');
require('core-js/modules/es.array.map.js');
require('core-js/modules/es.array.slice.js');
require('core-js/modules/es.array.sort.js');
require('core-js/modules/es.function.name.js');
require('core-js/modules/es.object.get-own-property-descriptor.js');
require('core-js/modules/es.object.get-own-property-descriptors.js');
require('core-js/modules/es.object.keys.js');
require('core-js/modules/es.object.to-string.js');
require('core-js/modules/es.promise.js');
require('core-js/modules/es.regexp.exec.js');
require('core-js/modules/es.string.includes.js');
require('core-js/modules/es.string.replace.js');
require('core-js/modules/web.dom-collections.for-each.js');
var dayjs = require('../../../utils/dayjs.js');
var index = require('../i18n/index.js');
var suiteHeaderData_fixture = require('./suiteHeaderData.fixture.js');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var _toConsumableArray__default = /*#__PURE__*/_interopDefault(_toConsumableArray);
var _slicedToArray__default = /*#__PURE__*/_interopDefault(_slicedToArray);
var _defineProperty__default = /*#__PURE__*/_interopDefault(_defineProperty);
var _asyncToGenerator__default = /*#__PURE__*/_interopDefault(_asyncToGenerator);
var _regeneratorRuntime__default = /*#__PURE__*/_interopDefault(_regeneratorRuntime);

function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty__default.default(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }

// default route calculation logic
var calcRoutes = function calcRoutes(domain, user, workspaces, applications) {
  var workspaceId = Object.keys(user.workspaces)[0];
  var getApplicationUrl = function getApplicationUrl(appId) {
    return user.workspaces[workspaceId].applications[appId].href;
  };
  var isAdmin = user.permissions.systemAdmin || user.permissions.userAdmin;
  var routeData = {
    profile: "https://home.".concat(domain, "/myaccount"),
    navigator: "https://".concat(workspaceId, ".home.").concat(domain),
    admin: isAdmin ? "https://admin.".concat(domain) : null,
    logout: "https://home.".concat(domain, "/logout"),
    whatsNew: 'https://www.ibm.com/support/knowledgecenter/SSRHPA_current/appsuite/overview/whats_new.html',
    gettingStarted: 'https://www.ibm.com/support/knowledgecenter/SSRHPA_current/appsuite/overview/getting_started.html',
    documentation: 'https://www.ibm.com/support/knowledgecenter/SSRHPA_current',
    requestEnhancement: 'https://ibm-watson-iot.ideas.aha.io/',
    support: 'https://www.ibm.com/mysupport',
    about: "https://home.".concat(domain, "/about"),
    workspaceId: workspaceId,
    domain: domain
  };
  var appOrdering = ['monitor', 'health', 'predict', 'visualinspection'];
  var workspaceApplications = user.workspaces[workspaceId].applications || {};
  var applicationSyncStates = user.applications || {};
  var appData = Object.keys(workspaceApplications).filter(function (appId) {
    return workspaceApplications[appId].role !== 'NO_ACCESS';
  }).filter(function (appId) {
    var _applicationSyncState;
    return ((_applicationSyncState = applicationSyncStates[appId]) === null || _applicationSyncState === void 0 || (_applicationSyncState = _applicationSyncState.sync) === null || _applicationSyncState === void 0 ? void 0 : _applicationSyncState.state) === 'SUCCESS';
  }).filter(function (appId) {
    return (applications.find(function (i) {
      return i.id === appId;
    }) || {}).category === 'application';
  }).sort(function (a, b) {
    return appOrdering.findIndex(function (i) {
      return i === a;
    }) - appOrdering.findIndex(function (i) {
      return i === b;
    });
  }).map(function (appId) {
    return {
      id: appId,
      name: (applications.find(function (i) {
        return i.id === appId;
      }) || {}).name || appId.charAt(0).toUpperCase() + appId.slice(1),
      href: getApplicationUrl(appId),
      isExternal: getApplicationUrl(appId).indexOf(domain) >= 0
    };
  }).sort();
  return [routeData, appData];
};

// Default survey status calculation logic
var calcSurveyStatus = /*#__PURE__*/function () {
  var _ref = _asyncToGenerator__default.default(/*#__PURE__*/_regeneratorRuntime__default.default.mark(function _callee(userId, surveyConfig, apiFct) {
    var showSurvey, isTimeForSurvey, surveyData, updateObject, _surveyConfig$delayIn, _surveyConfig$frequen, _surveyConfig$enabled;
    return _regeneratorRuntime__default.default.wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          showSurvey = false; // Check if it is time to show the survey
          isTimeForSurvey = function isTimeForSurvey(surveyData) {
            // If survey is not enabled, return false
            if (!surveyData.enabled) {
              return false;
            }
            // If lastPromptTimestamp is set and it is greater than initialInteractionTimestamp,
            // it means that at least one survey has already been prompted to the user,
            // so, we check if another survey prompt is due.
            if (surveyData.lastPromptTimestamp && dayjs.default(surveyData.lastPromptTimestamp).isAfter(surveyData.initialInteractionTimestamp)) {
              if (dayjs.default().diff(surveyData.lastPromptTimestamp, 'days') > surveyData.frequencyDays) {
                return true;
              }
            }
            // No survey has been prompted yet, so we check if it is time for the first one.
            else if (dayjs.default().diff(surveyData.initialInteractionTimestamp, 'days') > surveyData.delayIntervalDays) {
              return true;
            }
            return false;
          };
          _context.next = 4;
          return apiFct('GET', "/users/".concat(userId, "/surveys/").concat(surveyConfig.id));
        case 4:
          surveyData = _context.sent;
          if (!surveyData) {
            _context.next = 17;
            break;
          }
          // Survey data found, check it some config props need to be updated on the backend
          updateObject = {};
          ['delayIntervalDays', 'frequencyDays', 'enabled'].forEach(function (surveyProp) {
            if (surveyConfig[surveyProp] && surveyConfig[surveyProp] !== surveyData[surveyProp]) {
              updateObject[surveyProp] = surveyConfig[surveyProp];
            }
          });
          // If at least one config prop is different than the one in the existing record, update it
          if (!(Object.keys(updateObject).length > 0)) {
            _context.next = 11;
            break;
          }
          _context.next = 11;
          return apiFct('PUT', "/users/".concat(userId, "/surveys/").concat(surveyConfig.id), updateObject);
        case 11:
          // Based on survey data and current timestamp, make the proper time comparisons to check if it is time to show a survey
          showSurvey = isTimeForSurvey(surveyData);
          if (!showSurvey) {
            _context.next = 15;
            break;
          }
          _context.next = 15;
          return apiFct('PUT', "/users/".concat(userId, "/surveys/").concat(surveyConfig.id), {
            lastPromptTimestamp: dayjs.default.utc().format()
          });
        case 15:
          _context.next = 19;
          break;
        case 17:
          _context.next = 19;
          return apiFct('POST', "/users/".concat(userId, "/surveys"), _objectSpread(_objectSpread({}, surveyConfig), {}, {
            delayIntervalDays: (_surveyConfig$delayIn = surveyConfig.delayIntervalDays) !== null && _surveyConfig$delayIn !== void 0 ? _surveyConfig$delayIn : 30,
            frequencyDays: (_surveyConfig$frequen = surveyConfig.frequencyDays) !== null && _surveyConfig$frequen !== void 0 ? _surveyConfig$frequen : 90,
            enabled: (_surveyConfig$enabled = surveyConfig.enabled) !== null && _surveyConfig$enabled !== void 0 ? _surveyConfig$enabled : true,
            initialInteractionTimestamp: dayjs.default.utc().format()
          }));
        case 19:
          return _context.abrupt("return", showSurvey);
        case 20:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
  return function calcSurveyStatus(_x, _x2, _x3) {
    return _ref.apply(this, arguments);
  };
}();

// default i18n calculation logic
var calcI18N = function calcI18N(i18nData) {
  return _objectSpread(_objectSpread({}, i18nData), {}, {
    surveyTitle: function surveyTitle(solutionName) {
      return i18nData.surveyTitle.replace('{solutionName}', solutionName);
    },
    profileLogoutModalBody: function profileLogoutModalBody(solutionName, userName) {
      return i18nData.profileLogoutModalBody.replace('{solutionName}', solutionName).replace('{userName}', userName);
    }
  });
};
var defaultFetchApi = /*#__PURE__*/function () {
  var _ref2 = _asyncToGenerator__default.default(/*#__PURE__*/_regeneratorRuntime__default.default.mark(function _callee2(method, url, body, headers, testResponse) {
    return _regeneratorRuntime__default.default.wrap(function _callee2$(_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          return _context2.abrupt("return", testResponse || fetch(url, {
            method: method,
            credentials: 'include',
            headers: headers || {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(body)
          }).then(function (res) {
            return res.json();
          }).then(function (resJson) {
            // Don't return any data if an error happened (401, 404, 409, etc)
            if (resJson.error || resJson.exception) {
              return null;
            }
            return resJson;
          }));
        case 1:
        case "end":
          return _context2.stop();
      }
    }, _callee2);
  }));
  return function defaultFetchApi(_x4, _x5, _x6, _x7, _x8) {
    return _ref2.apply(this, arguments);
  };
}();
var getSuiteHeaderData = /*#__PURE__*/function () {
  var _ref4 = _asyncToGenerator__default.default(/*#__PURE__*/_regeneratorRuntime__default.default.mark(function _callee3(_ref3) {
    var _appconnectData$users, _profileData$user;
    var baseApiUrl, domain, _ref3$lang, lang, _ref3$calculateRoutes, calculateRoutes, _ref3$calculateSurvey, calculateSurveyStatus, _ref3$calculateI18N, calculateI18N, _ref3$fetchApi, fetchApi, _ref3$surveyConfig, surveyConfig, _ref3$isTest, isTest, api, profileData, appsData, eamData, mroioData, apmData, appconnectData, i18nData, _calculateRoutes, _calculateRoutes2, routes, applications, showSurvey, i18n, externalApps;
    return _regeneratorRuntime__default.default.wrap(function _callee3$(_context3) {
      while (1) switch (_context3.prev = _context3.next) {
        case 0:
          baseApiUrl = _ref3.baseApiUrl, domain = _ref3.domain, _ref3$lang = _ref3.lang, lang = _ref3$lang === void 0 ? 'en' : _ref3$lang, _ref3$calculateRoutes = _ref3.calculateRoutes, calculateRoutes = _ref3$calculateRoutes === void 0 ? calcRoutes : _ref3$calculateRoutes, _ref3$calculateSurvey = _ref3.calculateSurveyStatus, calculateSurveyStatus = _ref3$calculateSurvey === void 0 ? calcSurveyStatus : _ref3$calculateSurvey, _ref3$calculateI18N = _ref3.calculateI18N, calculateI18N = _ref3$calculateI18N === void 0 ? calcI18N : _ref3$calculateI18N, _ref3$fetchApi = _ref3.fetchApi, fetchApi = _ref3$fetchApi === void 0 ? defaultFetchApi : _ref3$fetchApi, _ref3$surveyConfig = _ref3.surveyConfig, surveyConfig = _ref3$surveyConfig === void 0 ? null : _ref3$surveyConfig, _ref3$isTest = _ref3.isTest, isTest = _ref3$isTest === void 0 ? false : _ref3$isTest;
          api = function api(method, path, body, headers) {
            return fetchApi(method, "".concat(baseApiUrl).concat(path), body, headers, isTest ? suiteHeaderData_fixture[path] : null);
          };
          _context3.next = 4;
          return api('GET', '/profile');
        case 4:
          profileData = _context3.sent;
          _context3.next = 7;
          return api('GET', '/applications');
        case 7:
          appsData = _context3.sent;
          _context3.next = 10;
          return api('GET', '/config/eam');
        case 10:
          eamData = _context3.sent;
          _context3.next = 13;
          return api('GET', '/config/mroio');
        case 13:
          mroioData = _context3.sent;
          _context3.next = 16;
          return api('GET', '/config/apm');
        case 16:
          apmData = _context3.sent;
          _context3.next = 19;
          return api('GET', '/config/appconnect');
        case 19:
          appconnectData = _context3.sent;
          _context3.next = 22;
          return api('GET', "/i18n/header/".concat(isTest ? 'en' : lang));
        case 22:
          i18nData = _context3.sent;
          // Routes
          _calculateRoutes = calculateRoutes(domain, profileData.user, profileData.workspaces, appsData), _calculateRoutes2 = _slicedToArray__default.default(_calculateRoutes, 2), routes = _calculateRoutes2[0], applications = _calculateRoutes2[1]; // Survey
          if (!(surveyConfig !== null && surveyConfig !== void 0 && surveyConfig.id)) {
            _context3.next = 30;
            break;
          }
          _context3.next = 27;
          return calculateSurveyStatus(profileData.user.username, surveyConfig, api);
        case 27:
          _context3.t0 = _context3.sent;
          _context3.next = 31;
          break;
        case 30:
          _context3.t0 = false;
        case 31:
          showSurvey = _context3.t0;
          // i18n
          i18n = i18nData ? calculateI18N(i18nData) : index.en; // apps to open in a new window
          externalApps = ['eam', 'mroio', 'digitaltwin', 'apm', 'visualinspection', 'appconnect'];
          return _context3.abrupt("return", {
            username: profileData.user.username,
            userDisplayName: profileData.user.displayName,
            email: profileData.user.email,
            routes: routes,
            applications: [].concat(_toConsumableArray__default.default(eamData !== null && eamData !== void 0 && eamData.url ? [{
              id: 'eam',
              name: 'Manage',
              href: eamData.url
            }] : []), _toConsumableArray__default.default(applications), _toConsumableArray__default.default(mroioData !== null && mroioData !== void 0 && mroioData.url ? [{
              id: 'mroio',
              name: 'MRO Inventory Optimization',
              href: mroioData.url
            }] : []), _toConsumableArray__default.default(((_appconnectData$users = appconnectData === null || appconnectData === void 0 ? void 0 : appconnectData.users) !== null && _appconnectData$users !== void 0 ? _appconnectData$users : []).includes(profileData === null || profileData === void 0 || (_profileData$user = profileData.user) === null || _profileData$user === void 0 ? void 0 : _profileData$user.username) ? [{
              id: 'appconnect',
              name: 'App Connect',
              href: appconnectData === null || appconnectData === void 0 ? void 0 : appconnectData.dashboard
            }] : []), _toConsumableArray__default.default(apmData !== null && apmData !== void 0 && apmData.dashboard ? [{
              id: 'apm',
              name: 'APM for E&U',
              href: apmData.dashboard
            }] : [])).map(function (app) {
              return _objectSpread(_objectSpread({}, app), {}, {
                isExternal: externalApps.includes(app.id)
              });
            }),
            i18n: i18n,
            showSurvey: showSurvey
          });
        case 35:
        case "end":
          return _context3.stop();
      }
    }, _callee3);
  }));
  return function getSuiteHeaderData(_x9) {
    return _ref4.apply(this, arguments);
  };
}();
var getSuiteHeaderData$1 = getSuiteHeaderData;

exports.calcI18N = calcI18N;
exports.calcRoutes = calcRoutes;
exports.calcSurveyStatus = calcSurveyStatus;
exports.default = getSuiteHeaderData$1;
exports.defaultFetchApi = defaultFetchApi;
