import {useEffect, useState} from 'react';

/** hook for handle big amounts of data on local on scroll */
export const useInfiniteScroll = (callback:any, element:any) => {

    const [isFetching, setIsFetching] = useState<boolean>(false);
    const [lastHeightDetected, setLastHeightDetected] = useState(null);
  
    useEffect(() => {
      const elementToWatch = element.current
      elementToWatch.addEventListener('scroll', handleScroll);
      return () => elementToWatch.removeEventListener('scroll', handleScroll);
    }, []);
  
    useEffect(() => {
      if (!isFetching) return;
      callback();
    }, [isFetching]);
  
    function handleScroll() {
      //console.log("element", element.current)
      if (element.current.scrollTop > (element.current.scrollHeight - (element.current.offsetHeight * 2.5)) && element.current.scrollTop != lastHeightDetected) {
        setIsFetching(true);
        setLastHeightDetected(element.current.scrollTop)
      }
    }
  
    return [isFetching, setIsFetching] as const;
  };