import _asyncToGenerator from '@babel/runtime/helpers/asyncToGenerator';
import _classCallCheck from '@babel/runtime/helpers/classCallCheck';
import _createClass from '@babel/runtime/helpers/createClass';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import _regeneratorRuntime from '@babel/runtime/regenerator';
import { R as Rendering, H as HQRenderScript } from './index-fe887b5f.js';
import DivaUtils, { DivaError } from '@crystaldesign/diva-utils';
import { HubConnectionBuilder, LogLevel } from '@microsoft/signalr';
import io from 'socket.io-client';
import { MessagePackHubProtocol } from '@microsoft/signalr-protocol-msgpack';
import '@babel/runtime/helpers/slicedToArray';
import '@babel/runtime/helpers/objectWithoutProperties';
import '@babel/runtime/helpers/toConsumableArray';
import 'axios';
import '@crystaldesign/basket-model';
import '@crystaldesign/basket-handler';
import '@babel/runtime/helpers/typeof';

var LOG = DivaUtils.initLog('Planner', 'WEB-PLANNER-LOGIC');
var Host3DSignalR = /*#__PURE__*/function () {
  function Host3DSignalR(renderSettings, plannerHandler3D) {
    var _this = this;
    _classCallCheck(this, Host3DSignalR);
    //SignalR Connection
    _defineProperty(this, "renderSettings", void 0);
    _defineProperty(this, "signalRConnection", void 0);
    _defineProperty(this, "connectionStarted", void 0);
    _defineProperty(this, "successfullyLoggedIn", void 0);
    _defineProperty(this, "connectionErrorCount", void 0);
    _defineProperty(this, "doIgnoreOnClosed", void 0);
    //This boolean allows to ignore the onClose connection event of the signalR connection.
    _defineProperty(this, "sessionID", void 0);
    //DivaMediaService
    _defineProperty(this, "divaMediaServiceSocketIO", undefined);
    _defineProperty(this, "lastJoinDivaNr", void 0);
    _defineProperty(this, "reconnectAfterError", void 0);
    _defineProperty(this, "successfullyJoinedDivaNr", void 0);
    //callbacks
    _defineProperty(this, "plannerHandler3D", void 0);
    _defineProperty(this, "reconnectingErrorCount", void 0);
    /**
     * This function initializes the Connection to the diva Media Service.
     * It is called when The webClient joints to a new DivaNr
     */
    _defineProperty(this, "openSocketToMediaService", function (divaNr) {
      // Close existing socket connection if it exists
      if (_this.divaMediaServiceSocketIO) {
        _this.divaMediaServiceSocketIO.disconnect();
        _this.divaMediaServiceSocketIO = undefined;
      }
      var socket = new URL(_this.renderSettings.DivaMediaServiceUrl + '/');
      var socketUrl = socket.origin + '?divaNrs=' + divaNr;
      _this.divaMediaServiceSocketIO = io(socketUrl, {
        forceNew: true,
        path: socket.pathname + 'socket.io',
        rejectUnauthorized: false
      });
      var that = _this;
      _this.divaMediaServiceSocketIO.on('connect', function (msg) {
        LOG.debug('Successfully connected to DivaMediaService with divaNr: ' + divaNr);
      });
      _this.divaMediaServiceSocketIO.on('disconnect', function () {
        LOG.debug('Disconnect from DivaMediaService with divaNr: ' + divaNr + ' and mediaServiceUrl: ' + _this.renderSettings.DivaMediaServiceUrl);
      });
      _this.divaMediaServiceSocketIO.on('connect_error', function (error) {
        LOG.debug('Socket CONNECT_ERROR:', error);
      });
      _this.divaMediaServiceSocketIO.on('reconnect', function (attemptNumber) {
        LOG.debug('Socket RECONNECTED, attempt:', attemptNumber);
      });

      //        this.divaMediaServiceSocketIO = require('socket.io')(server);
      _this.divaMediaServiceSocketIO.on('DIVA3D', function (msg) {
        // const transaction = DivaUtils.getApm()?.startTransaction('ON_REQUEST_RENDERING', undefined, { childOf: msg.traceId } as any);
        if (msg.hash && msg.hash != '') {
          // transaction?.end();
          that.plannerHandler3D.handleReceiveRendering({
            divaNr: msg.divaNr,
            hash: msg.hash,
            buffer: msg.buffer,
            url: msg.url,
            saveMode: msg.saveMode
          });
        }
      });
    });
    //------------------------------------------------------FUnctions called  from 3DHost - -----------------------------------------------
    /**
     * This function is called when a client asks for a rendering (Only update viewpoint) but no awailable render client has loaded the rendering
     * @param hash  The hash value of the requested planning
     * @param size  The size of the requested rendering
     * @param BG    The Background Info used for this rendering
     */
    _defineProperty(this, "noRenderClientFound", function (hash, size, option) {
      LOG.debug('No rendering client has loaded the planning - send new request and force reload!');
      DivaUtils.endSpanOfApm('PlannerHandler3D requestRenderingFromSignalR ' + hash);
      DivaUtils.endSpanOfApm('PlannerHandler3D requestRenderingDescriptionFromSignalR ' + hash);
      _this.plannerHandler3D.onErrorRequestingRendering(hash, size, option);
    });
    _defineProperty(this, "returnVPInfo", function (msg) {});
    /**
     * This function is called when a new Rendering is found.
     * @param divaNr    The divaNr of the rendering
     * @param hash      The unique identifier of the rendering
     * @param uiPolygon     The UIPolygon that holds additional information like the bounding box or camera position.
     */
    _defineProperty(this, "newRendering", function (divaNr, hash, uiPolygon) {
      LOG.debug('Receive UI Polygon: ' + uiPolygon);
      _this.plannerHandler3D.onReceivedAdditionalRenderInfo(hash, uiPolygon);
    });
    /**
     * This function is called when a new HqRenderscript is found.
     * @param divaNr    The divaNr of the rendering
     * @param hash      The unique identifier of the rendering
     * @param hqRenderScript     The HqRenderscript
     */
    _defineProperty(this, "newHQRenderScript", function (divaNr, hash, hqRenderScript) {
      LOG.debug('Receive HQRenderScript: ' + hqRenderScript);
      _this.plannerHandler3D.onReceiveHQRenderScript(hash, hqRenderScript);
    });
    /**
     * This function is called when a new Layer mask is rendered
     * @param divaNr    The divaNr the layer mask belongs too
     * @param hash      The hash value (unique identifier) of the associated rendering
     */
    _defineProperty(this, "newRenderingLayerMask", function (divaNr, hash) {
      DivaUtils.endSpanOfApm('PlannerHandler3D requestRenderingDescriptionFromSignalR ' + hash);
      LOG.debug('New Rendering Layer Mask finished hash: ' + hash);
    });
    this.renderSettings = renderSettings;
    this.connectionStarted = false;
    this.successfullyLoggedIn = false;
    this.successfullyJoinedDivaNr = false;
    this.connectionErrorCount = 0;
    this.reconnectAfterError = false;
    this.lastJoinDivaNr = '';
    this.doIgnoreOnClosed = false;
    this.plannerHandler3D = plannerHandler3D;
    this.sessionID = '';
    this.reconnectingErrorCount = 0;
  }

  /**
   * This function is used to initialize the SignalR Connection.
   */
  return _createClass(Host3DSignalR, [{
    key: "initializeConnection",
    value: (function () {
      var _initializeConnection = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(divaNr) {
        var _this2 = this;
        var that;
        return _regeneratorRuntime.wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              //  const { default: signalR } = await import("@microsoft/signalr");

              DivaUtils.startSpanOfApm('Host3DSingalR initializeConnection');

              //let test = new signalR.HubConnection(this.diva3DServerURL);
              if (!(this.reconnectingErrorCount > 0)) {
                _context2.next = 4;
                break;
              }
              _context2.next = 4;
              return this.delay(100);
            case 4:
              LOG.debug('Create SignalR connection with host: ' + this.renderSettings.Diva3DServerURL + '; RenderGroup: ' + this.renderSettings.RenderGroup);
              that = this;
              if (this.signalRConnection) {
                this.doIgnoreOnClosed = true;
                this.signalRConnection._completeClose();
                this.signalRConnection = null;
              }
              if ((typeof window === 'undefined' || window).DIVA_LOGGER == 0) {
                this.signalRConnection = new HubConnectionBuilder().withUrl(this.renderSettings.Diva3DServerURL).withHubProtocol(new MessagePackHubProtocol()).build();
              } else {
                this.signalRConnection = new HubConnectionBuilder().withUrl(this.renderSettings.Diva3DServerURL).withHubProtocol(new MessagePackHubProtocol()).configureLogging(LogLevel.None).build();
              }
              this.signalRConnection.on('UnvalidSessionID', this.unvalidSessionID);
              this.signalRConnection.on('noRenderClientFound', this.noRenderClientFound);
              this.signalRConnection.on('newRendering', this.newRendering);
              this.signalRConnection.on('newHQRenderScript', this.newHQRenderScript);
              this.signalRConnection.on('newRenderingLayerMask', this.newRenderingLayerMask);
              this.signalRConnection.start().then(function () {
                DivaUtils.endSpanOfApm('PlannerHandler3D initSignalRConnection');
                that.connectionStarted = true;
                that.doIgnoreOnClosed = false;
                if (that.reconnectAfterError) {
                  LOG.debug('SignalR Connection to 3DHost: ' + _this2.renderSettings.Diva3DServerURL + ' sucessfully reconnected', 'initSignalRConnection');
                } else {
                  LOG.debug('SignalR Connection to 3DHost: ' + that.renderSettings.Diva3DServerURL + ' sucessfully started', 'initSignalRConnection');
                }
                that.reconnectingErrorCount = 0;
                that.login(); //After connecting to signalR, the login should be performed
              })["catch"](function (err) {
                DivaUtils.endSpanOfApm('PlannerHandler3D initSignalRConnection');
                LOG.error(new DivaError('Connection error. Message: ' + err.toString(), {
                  code: 'WC_0014'
                }));
                that.connectionStarted = false;
                if (!that.successfullyLoggedIn || !that.successfullyJoinedDivaNr) {
                  that.reconnectingErrorCount++;
                  if (that.reconnectingErrorCount < 5) that.initializeConnection();
                }
              });
              this.signalRConnection.onclose(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
                return _regeneratorRuntime.wrap(function _callee$(_context) {
                  while (1) switch (_context.prev = _context.next) {
                    case 0:
                      DivaUtils.endSpanOfApm('PlannerHandler3D initSignalRConnection');
                      LOG.warn('Connection with 3D Host gets lost. Try to reconnect.', 'WC_0014');
                      that.connectionStarted = false;
                      _this2.successfullyLoggedIn = false;
                      _this2.successfullyJoinedDivaNr = false;
                      if (!_this2.doIgnoreOnClosed) {
                        _context.next = 7;
                        break;
                      }
                      return _context.abrupt("return");
                    case 7:
                      _this2.reconnectAfterError = true;
                      that.initializeConnection();
                    case 9:
                    case "end":
                      return _context.stop();
                  }
                }, _callee);
              })));
            case 15:
            case "end":
              return _context2.stop();
          }
        }, _callee2, this);
      }));
      function initializeConnection(_x) {
        return _initializeConnection.apply(this, arguments);
      }
      return initializeConnection;
    }())
  }, {
    key: "delay",
    value: function delay(ms) {
      return new Promise(function (resolve) {
        return setTimeout(resolve, ms);
      });
    }
  }, {
    key: "joinDivaNr",
    value: function () {
      var _joinDivaNr = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(divaNr) {
        return _regeneratorRuntime.wrap(function _callee3$(_context3) {
          while (1) switch (_context3.prev = _context3.next) {
            case 0:
              if (!(this.reconnectAfterError || this.lastJoinDivaNr != divaNr)) {
                _context3.next = 4;
                break;
              }
              _context3.next = 3;
              return this.join(divaNr);
            case 3:
              this.reconnectAfterError = false;
            case 4:
            case "end":
              return _context3.stop();
          }
        }, _callee3, this);
      }));
      function joinDivaNr(_x2) {
        return _joinDivaNr.apply(this, arguments);
      }
      return joinDivaNr;
    }()
  }, {
    key: "getSuccessfullyJoinedToDivaNr",
    value: function getSuccessfullyJoinedToDivaNr() {
      return this.successfullyJoinedDivaNr;
    }
  }, {
    key: "getViewPointInfo",
    value: function () {
      var _getViewPointInfo = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(vpName, standardWhiteroom) {
        var res;
        return _regeneratorRuntime.wrap(function _callee4$(_context4) {
          while (1) switch (_context4.prev = _context4.next) {
            case 0:
              _context4.prev = 0;
              _context4.next = 3;
              return this.signalRConnection.invoke('GetVPInfo', this.sessionID, standardWhiteroom, vpName);
            case 3:
              res = _context4.sent;
              return _context4.abrupt("return", res);
            case 7:
              _context4.prev = 7;
              _context4.t0 = _context4["catch"](0);
              LOG.error(new DivaError('DoUpdate 3D Host', {
                code: 'WC_0014'
              }));
            case 10:
            case "end":
              return _context4.stop();
          }
        }, _callee4, this, [[0, 7]]);
      }));
      function getViewPointInfo(_x3, _x4) {
        return _getViewPointInfo.apply(this, arguments);
      }
      return getViewPointInfo;
    }()
  }, {
    key: "getConnectionReady",
    value: function getConnectionReady() {
      return this.connectionIsReady();
    }
  }, {
    key: "getStaticRoomListInfo",
    value: function () {
      var _getStaticRoomListInfo = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee5(staticRoomList) {
        var that;
        return _regeneratorRuntime.wrap(function _callee5$(_context5) {
          while (1) switch (_context5.prev = _context5.next) {
            case 0:
              if (!this.connectionIsReady()) {
                that = this;
                setTimeout(function () {
                  return that.getStaticRoomListInfo(staticRoomList);
                }, 400);
              }
              LOG.debug('DIVA3D-HOST.SignaR POST GetFrontendRoomList - sessionID:' + this.sessionID);
              _context5.next = 4;
              return this.signalRConnection.invoke('GetFrontendRoomlist', this.sessionID, staticRoomList);
            case 4:
              return _context5.abrupt("return", _context5.sent);
            case 5:
            case "end":
              return _context5.stop();
          }
        }, _callee5, this);
      }));
      function getStaticRoomListInfo(_x5) {
        return _getStaticRoomListInfo.apply(this, arguments);
      }
      return getStaticRoomListInfo;
    }()
  }, {
    key: "request3D",
    value: function request3D(params) {
      var that = this;
      if (!this.connectionIsReady() || !this.successfullyJoinedDivaNr) {
        //If connection is not ready or WebClient not successfully logged in - always force reload whole planning
        params.doReloadWholePlanning = true;
        setTimeout(function () {
          return that.request3D(params);
        }, 300);
        //request new rendering only if the webPlanner in not already waiting for it or if the mediaServiceMode have changed from STREAM to TEMP
      } else {
        var _params$requestRender14;
        var rendering = undefined;
        var hqRenderScript = undefined;
        if (params !== null && params !== void 0 && params.doRequestRendering) {
          var _params$requestRender, _params$requestRender2, _params$requestRender3, _params$requestRender4, _params$requestRender5, _params$requestRender6, _params$requestRender7, _params$requestRender8, _params$requestRender9, _params$requestRender10, _params$requestRender11, _params$requestRender12, _params$requestRender13;
          rendering = new Rendering(params.planningHash, params.renderHash, (_params$requestRender = params.requestRenderingParams) === null || _params$requestRender === void 0 ? void 0 : _params$requestRender.viewPointName, (_params$requestRender2 = params.requestRenderingParams) === null || _params$requestRender2 === void 0 ? void 0 : _params$requestRender2.width, (_params$requestRender3 = params.requestRenderingParams) === null || _params$requestRender3 === void 0 ? void 0 : _params$requestRender3.height, (_params$requestRender4 = params.requestRenderingParams) === null || _params$requestRender4 === void 0 ? void 0 : _params$requestRender4.isFullscreenRendering, (_params$requestRender5 = params.requestRenderingParams) === null || _params$requestRender5 === void 0 ? void 0 : _params$requestRender5.hasDimensionLines, (_params$requestRender6 = params.requestRenderingParams) === null || _params$requestRender6 === void 0 ? void 0 : _params$requestRender6.plannerMeasureDigits, (_params$requestRender7 = params.requestRenderingParams) === null || _params$requestRender7 === void 0 ? void 0 : _params$requestRender7.planner3DGridEnabled, (_params$requestRender8 = params.requestRenderingParams) !== null && _params$requestRender8 !== void 0 && _params$requestRender8.viewPointInfo ? params.requestRenderingParams.viewPointInfo.isStatic : false, (_params$requestRender9 = params.requestRenderingParams) === null || _params$requestRender9 === void 0 ? void 0 : _params$requestRender9.mediaServiceSaveMode, (_params$requestRender10 = params.requestRenderingParams) === null || _params$requestRender10 === void 0 ? void 0 : _params$requestRender10.alternateRenderingsExist, (_params$requestRender11 = params.requestRenderingParams) === null || _params$requestRender11 === void 0 ? void 0 : _params$requestRender11.alternateRenderInfo);
          rendering.CatalogCodex = (_params$requestRender12 = params.requestRenderingParams) === null || _params$requestRender12 === void 0 ? void 0 : _params$requestRender12.catalogData.catalogCodex;
          rendering.CatalogGUID = (_params$requestRender13 = params.requestRenderingParams) === null || _params$requestRender13 === void 0 ? void 0 : _params$requestRender13.catalogData.catalogGUID;
        }
        if (params.doRequestHqRenderScript) {
          hqRenderScript = new HQRenderScript(params.planningHash);
        }

        //Create options Request
        var options3DHost = this.create3DHostRequestOption(params);
        LOG.debug('request 3D (mediaType ' + ((_params$requestRender14 = params.requestRenderingParams) === null || _params$requestRender14 === void 0 ? void 0 : _params$requestRender14.mediaServiceSaveMode) + ') from 3D Host' + JSON.stringify(params));
        if (params.doReloadWholePlanning) {
          LOG.debug('Host3DSignalR SaveProjectWithOptions');
          this.signalRConnection.invoke('SaveProjectWithOptions', this.sessionID, params.divaNr, JSON.stringify(params.planningData), this.renderSettings.RenderGroup, JSON.stringify(options3DHost));
        } else {
          this.signalRConnection.invoke('RequestRenderingWithOptions', this.sessionID, params.divaNr, options3DHost.VPName, options3DHost.VPSize, params.renderHash, JSON.stringify(options3DHost));
        }
        return {
          rendering: rendering,
          hqRenderScript: hqRenderScript
        };
      }
      return {
        rendering: undefined,
        hqRenderScript: undefined
      };
    }
  }, {
    key: "create3DHostRequestOption",
    value: function create3DHostRequestOption(params) {
      var _params$requestRender15, _params$requestRender16, _params$requestRender17, _params$requestRender18, _params$requestRender19, _params$requestRender20, _params$requestRender21, _params$requestRender22, _params$requestRender23, _params$requestRender24, _params$requestRender25, _params$requestRender26, _params$requestRender27, _params$requestRender28, _params$requestRender29, _params$requestRender30, _params$requestRender31;
      var size = params.requestRenderingParams ? params.requestRenderingParams.width + ':' + params.requestRenderingParams.height : '';
      var bgMode = params !== null && params !== void 0 && params.doRequestRendering && (_params$requestRender15 = params.requestRenderingParams) !== null && _params$requestRender15 !== void 0 && _params$requestRender15.planner3DGridEnabled ? 'layermask' : '';
      var signalRSavingMode = params !== null && params !== void 0 && params.doRequestRendering ? ((_params$requestRender16 = params.requestRenderingParams) === null || _params$requestRender16 === void 0 ? void 0 : _params$requestRender16.mediaServiceSaveMode) == 'STREAM' ? 0 : ((_params$requestRender17 = params.requestRenderingParams) === null || _params$requestRender17 === void 0 ? void 0 : _params$requestRender17.mediaServiceSaveMode) == 'PERMANENT' ? 1 : -1 : -1;
      var functionType = '';
      if (params.requestRenderingParams && params.requestRenderingParams.functionType) functionType = params.requestRenderingParams.functionType;
      var articleCodices = '[]';
      if (params !== null && params !== void 0 && params.doRequestRendering && (_params$requestRender18 = params.requestRenderingParams) !== null && _params$requestRender18 !== void 0 && _params$requestRender18.articleCodices) {
        articleCodices = '[';
        for (var i = 0; i < params.requestRenderingParams.articleCodices.length; i++) {
          articleCodices += '"' + params.requestRenderingParams.articleCodices[i] + '"' + (i < params.requestRenderingParams.articleCodices.length - 1 ? ',' : '');
        }
        articleCodices += ']';
      }
      var options = {
        rendering: params === null || params === void 0 ? void 0 : params.doRequestRendering,
        hqrenderscript: params.doRequestHqRenderScript,
        VPName: (_params$requestRender19 = (_params$requestRender20 = params.requestRenderingParams) === null || _params$requestRender20 === void 0 ? void 0 : _params$requestRender20.viewPointName) !== null && _params$requestRender19 !== void 0 ? _params$requestRender19 : '',
        VPSize: size,
        VPFilename: params.renderHash,
        PlanningHash: params.planningHash,
        RenderHash: params.renderHash,
        plannerMeasureDigits: (_params$requestRender21 = (_params$requestRender22 = params.requestRenderingParams) === null || _params$requestRender22 === void 0 ? void 0 : _params$requestRender22.plannerMeasureDigits) !== null && _params$requestRender21 !== void 0 ? _params$requestRender21 : 0,
        Format: 'JPG',
        BG: bgMode,
        MSSM: signalRSavingMode,
        OrgId: this.renderSettings.OrganizationId,
        FunctionType: functionType,
        CatalogCodex: (_params$requestRender23 = (_params$requestRender24 = params.requestRenderingParams) === null || _params$requestRender24 === void 0 ? void 0 : _params$requestRender24.catalogData.catalogCodex) !== null && _params$requestRender23 !== void 0 ? _params$requestRender23 : '',
        CatalogGuid: (_params$requestRender25 = (_params$requestRender26 = params.requestRenderingParams) === null || _params$requestRender26 === void 0 ? void 0 : _params$requestRender26.catalogData.catalogGUID) !== null && _params$requestRender25 !== void 0 ? _params$requestRender25 : '',
        ArticleCodices: (_params$requestRender27 = (_params$requestRender28 = params.requestRenderingParams) === null || _params$requestRender28 === void 0 ? void 0 : _params$requestRender28.articleCodices) !== null && _params$requestRender27 !== void 0 ? _params$requestRender27 : [],
        UserSessionId: DivaUtils.SessionId,
        v: (_params$requestRender29 = (_params$requestRender30 = params.requestRenderingParams) === null || _params$requestRender30 === void 0 ? void 0 : _params$requestRender30.catalogData.catalogGUID) !== null && _params$requestRender29 !== void 0 ? _params$requestRender29 : '',
        hybrid3DInfo: (_params$requestRender31 = params.requestRenderingParams) === null || _params$requestRender31 === void 0 ? void 0 : _params$requestRender31.hybrid3DInfo
      };
      return options;
    }
  }, {
    key: "closeConnection",
    value: function closeConnection() {
      if (this.signalRConnection) {
        this.doIgnoreOnClosed = true;
        this.signalRConnection.invoke('LeaveWebClient');
        LOG.debug('SignalRConnection: Close Connection and say byby to Diva3DHost.');
        this.signalRConnection.completeClose();
      }

      // Also close the socket connection to DivaMediaService
      if (this.divaMediaServiceSocketIO) {
        LOG.debug('Closing DivaMediaService socket connection');
        this.divaMediaServiceSocketIO.disconnect();
        this.divaMediaServiceSocketIO = undefined;
      }
    }

    /**
     * This function is called to login To the SignalR connection.
     * Make shure the connection is established yet
     */
  }, {
    key: "login",
    value: (function () {
      var _login = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee6() {
        var sessionId, that;
        return _regeneratorRuntime.wrap(function _callee6$(_context6) {
          while (1) switch (_context6.prev = _context6.next) {
            case 0:
              LOG.debug('DIVA3D-HOST.SignaR POST Login - userID:' + this.renderSettings.UserID + ', deviceID:' + this.renderSettings.DeviceID + ', divaSessionID:' + this.renderSettings.DivaSessionID + ', _Application:' + this.renderSettings.ApplicationName);
              //_this.ServerLog("Login","send Login - userID:" + _userID + ", deviceID:" + _deviceID + ", divaSessionID:" SaveProjectWi+ _divaSessionID + ", info:" + _Application);
              DivaUtils.startSpanOfApm('PlannerHandler3D login');
              _context6.prev = 2;
              _context6.next = 5;
              return this.signalRConnection.invoke('LoginWebPlanner', this.renderSettings.UserID, this.renderSettings.DeviceID, this.renderSettings.DivaSessionID, this.renderSettings.ApplicationName);
            case 5:
              sessionId = _context6.sent;
              this.connectionErrorCount = 0;
              if (sessionId != '') {
                this.successfullyLoggedIn = true;
                LOG.debug('DIVA3D-HOST.SignaR Response ReturnLogin - sessionID: ' + sessionId);
                this.sessionID = sessionId;
                this.plannerHandler3D.onConnectionInitialized({
                  status: 'SUCCESSFULL'
                });
              } else {
                this.plannerHandler3D.onConnectionInitialized({
                  status: 'ERROR'
                });
              }
              _context6.next = 15;
              break;
            case 10:
              _context6.prev = 10;
              _context6.t0 = _context6["catch"](2);
              DivaUtils.endSpanOfApm('PlannerHandler3D login');
              that = this;
              this.handleConnectionError(_context6.t0, function () {
                that.login();
              });
            case 15:
            case "end":
              return _context6.stop();
          }
        }, _callee6, this, [[2, 10]]);
      }));
      function login() {
        return _login.apply(this, arguments);
      }
      return login;
    }()
    /**
     * This function handels the join to a Diva Nr.
     * This function calls the method on the SignalR to join to the DivaNr
     * This function handles connection to the DivaMediaService
     * @param divaNr
     */
    )
  }, {
    key: "join",
    value: (function () {
      var _join = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee7(divaNr) {
        var that, success;
        return _regeneratorRuntime.wrap(function _callee7$(_context7) {
          while (1) switch (_context7.prev = _context7.next) {
            case 0:
              if (!(divaNr == '')) {
                _context7.next = 2;
                break;
              }
              return _context7.abrupt("return");
            case 2:
              if (this.lastJoinDivaNr != divaNr) {
                //Manage connection to DivaMediaService
                this.openSocketToMediaService(divaNr);
              }
              that = this;
              if (this.connectionIsReady()) {
                _context7.next = 8;
                break;
              }
              setTimeout(function () {
                that.join(divaNr);
              }, 200);
              _context7.next = 23;
              break;
            case 8:
              this.lastJoinDivaNr = divaNr;
              DivaUtils.startSpanOfApm('PlannerHandler3D join');
              LOG.debug('PlannerHandler3D SignalR - Join DivaNr to connected host: ' + divaNr);
              _context7.prev = 11;
              _context7.next = 14;
              return this.signalRConnection.invoke('JoinWebPlanner', this.sessionID, divaNr);
            case 14:
              success = _context7.sent;
              DivaUtils.endSpanOfApm('PlannerHandler3D join');
              if (success) {
                this.successfullyJoinedDivaNr = true;
                this.plannerHandler3D.onConnectedToDivaNr('SUCCESSFULL');
                LOG.debug('Return Join - Join successfull.');
              } else {
                this.join(divaNr);
              }
              this.connectionErrorCount = 0;
              _context7.next = 23;
              break;
            case 20:
              _context7.prev = 20;
              _context7.t0 = _context7["catch"](11);
              this.handleConnectionError(_context7.t0, function () {
                that.join(divaNr);
              });
            case 23:
            case "end":
              return _context7.stop();
          }
        }, _callee7, this, [[11, 20]]);
      }));
      function join(_x6) {
        return _join.apply(this, arguments);
      }
      return join;
    }())
  }, {
    key: "handleConnectionError",
    value:
    /**
     * This function is called to handle Connection Errors
     * @param error
     * @param callback
     */
    function handleConnectionError(error, callback) {
      this.connectionErrorCount++;
      if (this.connectionErrorCount == 4) {
        LOG.debug('SignalR Error. not possible to establish SignalR connection.');
      } else {
        LOG.debug('SignalR Error. Message: ' + error.message);
        // ConnectToServer(callback);
      }
    }

    /**
     * Returns true when the SignalR connection is ready and the client is successfully logged in.
     */
  }, {
    key: "connectionIsReady",
    value: function connectionIsReady() {
      return this.connectionStarted && this.successfullyLoggedIn;
    }
  }, {
    key: "unvalidSessionID",
    value:
    /**
     * This function is called from the host when the used sessionID is not valid anymore. In this case the client is not successfully logged in anymore.
     * @param hub
     * @param msg
     */
    function unvalidSessionID(hub, msg) {
      LOG.debug('DIVA3D-HOST.SignaR Response Unvalid SessionID');
      //debugErr(null, "DIVA3D-HOST.SignaR Response Unvalid SessionID", false, "UnvalidSessionID");
      //_this.ServerLog("UnvalidSessionID", "received " + msg);
      this.successfullyLoggedIn = false;
      //_this.LoginLoop();
    }
  }]);
}();

export { Host3DSignalR as default };
