'use strict';

var stringResources = require('./stringResources.js');

function isNumber(value) {
  return typeof value === "number" && isFinite(value);
}
function secondsToMilliseconds(seconds) {
  return seconds * 1e3;
}
function ServiceClientSentinel(serviceClient, clientID, sessionTimeoutSeconds) {
  if (!serviceClient) {
    throw stringResources.stringResources.noServiceClient;
  }
  if (!isNumber(sessionTimeoutSeconds)) {
    throw "sessionTimeoutSeconds must a number and must be finite";
  }
  var interval;
  var pingMilliseconds;
  if (sessionTimeoutSeconds <= 120) {
    pingMilliseconds = secondsToMilliseconds(sessionTimeoutSeconds) / 2;
  } else {
    pingMilliseconds = secondsToMilliseconds(sessionTimeoutSeconds - 60);
  }
  function start() {
    if (pingMilliseconds <= 0) {
      return;
    }
    pingMilliseconds = Math.min(pingMilliseconds, 2147483647);
    interval = setInterval(() => {
      serviceClient.keepClientAlive(clientID);
    }, pingMilliseconds);
  }
  function restart() {
    stop();
    start();
  }
  function stop() {
    if (interval) {
      clearInterval(interval);
      interval = null;
    }
  }
  return {
    start,
    restart,
    stop
  };
}

exports.ServiceClientSentinel = ServiceClientSentinel;
