import {useEffect, useRef, DependencyList} from 'react';

type UsePollingEffectOptions = {
    interval?: number;
    isActive?: boolean;
    onCleanUp?: () => void;
};

function usePollingEffect(
    asyncCallback: () => Promise<void>,
    dependencies: DependencyList = [],
    options: UsePollingEffectOptions = {}
): void {
    const {
        interval = 3000,
        isActive = true,
        onCleanUp = () => {
        }
    } = options;

    const timeoutIdRef = useRef<number | null>(null);

    useEffect(() => {
        if (!isActive) { // If not active, don't do anything
            return;
        }

        let stopped = false;

        const pollingCallback = async () => {
            try {
                await asyncCallback();
            } finally {
                if (!stopped) {
                    timeoutIdRef.current = setTimeout(pollingCallback, interval);
                }
            }
        };

        // Immediately invoke the polling callback when the effect runs
        pollingCallback();

        // Clean up function to clear the timeout if the component unmounts or dependencies change
        return () => {
            stopped = true; // This will prevent new timeouts from being scheduled
            if (timeoutIdRef.current) {
                clearTimeout(timeoutIdRef.current);
            }
            onCleanUp();
        };
    }, [...dependencies, interval, isActive]); // dependencies array spread with interval
}

export default usePollingEffect;
