let initLocalTime = null;
let initServerTime = null;

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

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

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

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

export { initSyncTime, fetchTime };
