"use strict";

var _Object$defineProperty = require("@babel/runtime-corejs2/core-js/object/define-property");
_Object$defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _types = require("../../common/types");
/* eslint-env worker */

var keepaliveTimer;
var keepAliveRetryCount = 0;
var keepaliveInFlight = false;
var clearKeepaliveTimer = function clearKeepaliveTimer() {
  if (keepaliveTimer) {
    clearInterval(keepaliveTimer);
    keepaliveTimer = undefined;
  }
};
var messageHandler = function messageHandler(event) {
  var type = event.data.type;
  if (type === _types.WorkerMessageType.START_KEEPALIVE) {
    var _event$data = event.data,
      interval = _event$data.interval,
      retryCountThreshold = _event$data.retryCountThreshold;
    clearKeepaliveTimer();
    keepAliveRetryCount = 0;
    keepaliveInFlight = false;
    keepaliveTimer = setInterval(function () {
      if (keepAliveRetryCount < retryCountThreshold && !keepaliveInFlight) {
        keepaliveInFlight = true;
        postMessage({
          type: _types.WorkerMessageType.SEND_KEEPALIVE
        });
      }
    }, interval * 1000);
  }
  if (type === _types.WorkerMessageType.KEEPALIVE_RESULT) {
    keepaliveInFlight = false;
    if (event.data.err === undefined) {
      if (keepAliveRetryCount > 0) {
        postMessage({
          type: _types.WorkerMessageType.KEEPALIVE_SUCCESS,
          statusCode: event.data.statusCode
        });
      }
      keepAliveRetryCount = 0;
    } else {
      keepAliveRetryCount += 1;
      postMessage({
        type: _types.WorkerMessageType.KEEPALIVE_FAILURE,
        err: event.data.err,
        keepAliveRetryCount: keepAliveRetryCount
      });
    }
  }
  if (type === _types.WorkerMessageType.CLEAR_KEEPALIVE) {
    clearKeepaliveTimer();
    keepAliveRetryCount = 0;
    keepaliveInFlight = false;
  }
};

// eslint-disable-next-line no-restricted-globals
self.addEventListener('message', messageHandler);
var _default = exports.default = messageHandler;
//# sourceMappingURL=webWorker.js.map
