import { isPromise } from "@/app/library/library";
import { useCallback, useEffect, useMemo, useRef } from "react";

export const useInterval = (callback, delay, autostart) => {
  const savedCallback = useRef();
  const idInterval = useRef();

  useEffect(() => {
    savedCallback.current = callback;
  }, [callback]);

  const stopInterval = useCallback(() => {
    clearInterval(idInterval.current);
  }, []);

  const execute = useCallback(async () => {
    try {
      const isPromiseCallback = isPromise(savedCallback.current);
      if (isPromiseCallback) return await savedCallback.current();

      return savedCallback.current();
    } catch (error) {
      stopInterval();
    }
  }, [savedCallback, stopInterval]);

  const initial = useMemo(() => {
    if (autostart) {
      execute();
    }

    return execute;
  }, [execute, autostart]);

  useEffect(() => {
    if (delay === null) return;

    if (autostart) {
      const id = setInterval(execute, delay);
      idInterval.current = id;
    }

    return () => clearInterval(idInterval.current);
  }, [delay, execute, savedCallback, autostart]);

  return { stopInterval, initial };
};
