import { Dispatch, SetStateAction, useCallback, useEffect, useRef, useState } from "react";

export type Refresh = () => void;

/**
 * 
 * @returns `() => void` Function to trigger a new refresh. Set this as a dependency to watch for changes.
 */
export function useRefresh() : Refresh {
  const [instance, setInstance] = useState(0);

  const performRefresh = useCallback(() => {
    setInstance((x) => ++x);
  }, [instance]);

  return performRefresh;
}


/**
 * Helper function to convert to legacy refresh system when interacting with components, by storing and returning a number.
 * @param refresh 
 * @returns Signature of legacy refresh states.
 */
export function convertToLegacyRefresh(refresh: Refresh) : [number, Dispatch<SetStateAction<number>>] {
    const [val, setVal] = useState(0);

    useEffect(() => {
      if(initialized.current) {
        setVal(x => ++x);
      } else {
        initialized.current = true;
      }
    }, [refresh]);

    const initialized = useRef(false);
    
    const trigger : Dispatch<SetStateAction<number>> = useCallback(() => {
        refresh();
    },[]);

    return [val, trigger];
}