(function (window, document) {
  var eventUrl = "/awecloud/api/events/token/subscribe";
  var pingUrl = "/awecloud/api/events/token/publish?state=ping";
  var evtSource = new EventSource(eventUrl);
  evtSource.addEventListener("message", function (e) {
    console.log("message:", e);
    if (e.data == "timeout") {
      location.href = "/awecloud/dex/logout?ReturnUrl=" + encodeURIComponent(location.href);
    } else if (e.data == "new_login") {
      location.href = "/awecloud/dex/logout?ReturnUrl=" + encodeURIComponent(location.href);
    }
  });

  var pingFn = function () {
    var req = new XMLHttpRequest();
    req.open("GET", pingUrl);
    req.send();
  };

  var nowFn = function () {
    return new Date().getTime();
  };
  var lastActTime = nowFn();
  var interval = 10000;
  var pingTimerFn = function () {
    if (nowFn() - lastActTime < interval) {
      pingFn();
    }
    setTimeout(pingTimerFn, interval);
  };
  pingTimerFn();

  var listenMouseover = function () {
    document.body.addEventListener("mouseover", function (e) {
      lastActTime = nowFn();
    });
  };

  if (document.body) {
    listenMouseover();
  } else {
    window.addEventListener("load", listenMouseover);
  }
})(window, document);
