/*
 * @Author: 赵伟
 * @Date: 2024-10-10 08:51:41
 * @Description: 服务器时间 hook
 */

import { getSeverTimeReq } from '@/services/experiment';
import { to } from '@/utils/promise';
import { useCallback, useEffect, useState } from 'react';

let globalTimeOffset: number | undefined = undefined;

export const globalGetSeverTime = async () => {
  const requestStartTime = Date.now();
  const [res] = await to(getSeverTimeReq());
  const requestEndTime = Date.now();
  const requestDuration = (requestEndTime - requestStartTime) / 2;
  if (res && res.data) {
    const serverDate = new Date(res.data);
    const timeOffset = serverDate.getTime() + requestDuration - requestEndTime;
    globalTimeOffset = timeOffset;
    return timeOffset;
  }
};

export const now = () => {
  return new Date(Date.now() + (globalTimeOffset ?? 0));
};

/** 获取服务器时间 */
export function useServerTime() {
  const [timeOffset, setTimeOffset] = useState<number>(globalTimeOffset ?? 0);

  useEffect(() => {
    const getSeverTime = async () => {
      const [res] = await to(globalGetSeverTime());
      if (res) {
        setTimeOffset(res);
      }
    };

    // 获取服务器时间，防止第一次加载时，请求失败
    if (!globalTimeOffset) {
      getSeverTime();
    }
  }, []);

  const now = useCallback(() => {
    return new Date(Date.now() + timeOffset);
  }, [timeOffset]);

  return [now] as const;
}
