import React from 'react';

const DEFAULT_AUTO_REFRESH_TIME = 10_000;

export function useAutoRefreshFlag({
  initialFlag = false,
  autoStopTimeMs = DEFAULT_AUTO_REFRESH_TIME,
  onStopByTimeout,
}: {
  initialFlag?: boolean;
  autoStopTimeMs?: number;
  onStopByTimeout?(): void;
} = {}) {
  const callbackRef = React.useRef(onStopByTimeout);
  const timeoutRef = React.useRef(0);
  const [shouldAutoRefresh, setShouldAutoRefresh] = React.useState(initialFlag);

  return React.useMemo(
    () => ({
      timeOutId: timeoutRef.current,
      isRefreshing: shouldAutoRefresh,
      trigger: () => {
        setShouldAutoRefresh(true);
        timeoutRef.current = window.setTimeout(() => {
          if (!shouldAutoRefresh) {
            setShouldAutoRefresh(false);
            if (callbackRef.current) {
              callbackRef.current();
            }
          }
        }, autoStopTimeMs);
      },
      stop: () => {
        setShouldAutoRefresh(false);
        clearTimeout(timeoutRef.current);
      },
    }),
    [shouldAutoRefresh, autoStopTimeMs],
  );
}
