import {useState, useRef, useEffect} from 'react';
import { useHistory } from 'react-router-dom';

export const useInfiniteLoading = ((props) => {
  const { getItems } = props;
  const [items, setItems] = useState([]);
  const initialPage = useRef(new URLSearchParams(window.location.search).get('page') || 1);
  const lowestPageLoaded = useRef(initialPage.current);
  const highestPageLoaded = useRef(initialPage.current); 
  const initialPageLoaded = useRef(false);
  const [hasNext, setHasNext] = useState(true);
  const [hasPrevious, setHasPrevious] = useState(() => initialPage.current > 1);
  const history = useHistory();

  const loadItems = async (page, itemCombineMethod) => {
    const data = await getItems({ page });
    setHasNext(data.totalPages > page)
    setHasPrevious(page > 1)
    setItems(prevItems => {
      return itemCombineMethod === 'prepend' ? 
      [...data.items, ...prevItems] : 
      [...prevItems, ...data.items]
    })
  }

  const loadNext = () => {
    const nextPage = highestPageLoaded.current + 1;
    history.replace(`?page=${nextPage}`);
    loadItems(nextPage, 'append');
    highestPageLoaded.current = nextPage;
  }

  const loadPrevoius = () => {
    const nextPage = lowestPageLoaded.current - 1;
    if (nextPage < 1) return;
    history.replace(`?page=${nextPage}`);
    loadItems(nextPage, 'prepend');
    lowestPageLoaded.current = nextPage;
  }

  useEffect(() => {
    if(initialPageLoaded.current){
      return
    }
    loadItems(initialPage.current, 'append');
    initialPageLoaded.current = true
  }, [loadItems])

  return{
    items,
    hasNext,
    hasPrevious,
    loadNext,
    loadPrevoius
  }
})