/* eslint-disable react-hooks/exhaustive-deps */
import { MutableRefObject, useEffect } from 'react';

import { addEventListeners, removeEventListeners } from './handle-event-listeners';

interface EventListeners {
  scrollTarget: MutableRefObject<HTMLElement | null>;
  onScroll: () => void;
  onTouchStart: () => void;
  onTouchMove: () => void;
  onTouchEnd: () => void;
}
export const useScrollEventListeners = ({
  scrollTarget,
  onScroll,
  onTouchStart,
  onTouchMove,
  onTouchEnd,
}: EventListeners) => {
  useEffect(() => {
    if(!scrollTarget.current){
      return () => {};
    }
    addEventListeners({ element: scrollTarget.current, onScroll, onTouchStart, onTouchMove, onTouchEnd });

    return () => {
      const rootEl = document.getElementById('root') as HTMLElement;
      const pullToRefreshEl = document.getElementsByClassName('ptr__children')[0] as HTMLElement;
      removeEventListeners({ element: rootEl, onScroll, onTouchStart, onTouchMove, onTouchEnd });
      removeEventListeners({ element: pullToRefreshEl, onScroll, onTouchStart, onTouchMove, onTouchEnd });
    };
  }, []);
};
