let initLocalTime = 0;
let initServerTime = 0;

function getStorgeTime(): number[] {
  const st = localStorage.getItem('st') || '';
  const unvalidVals = ['Infinity', 'NaN', 'null', 'undefined'];
  if (unvalidVals.includes(`${st}`)) {
    return [Date.now(), Date.now()];
  }

  const [s, t] = st.split('_');
  return [Number(s), Number(t)];
}

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

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

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

export { initSyncTime, fetchTime };
