let initLocalTime: number = 0;
let initServerTime: number = 0;

function getStorgeTime() {
  let st: string = localStorage.getItem("st") || "";
  const unvalidVals = ["Infinity", "NaN", "null", "undefined"];
  if (unvalidVals.includes(st + "")) {
    return [Date.now(), Date.now()];
  } else {
    const [s, t]: any = st.split("_");
    return [s * 1, t * 1];
  }
}

const [serverTime, localTime] = getStorgeTime();
initSyncTime(serverTime, localTime);

function initSyncTime(serverTime: number, localTime = Date.now()) {
  initLocalTime = localTime;
  initServerTime = serverTime;
  localStorage.setItem("st", `${initServerTime}_${initLocalTime}`);
}

function fetchTime() {
  return Date.now() + (initServerTime - initLocalTime || 0);
}

export { initSyncTime, fetchTime };
