import { useCallback, useRef, useState } from 'react';

export function useSelectGroup<T>(): [
   (resourceId: any, select?: boolean) => void,
   () => void,
   Map<number, T>,
   (resourceId: any) => boolean,
] {
   const [selected, setSelected] = useState(new Map());
   const selectedRef = useRef(selected);

   const onSelect = useCallback((resourceId, select = true) => {
      setSelected((draft) => {
         const newSelected = new Map(draft);

         if (select) {
            newSelected.set(resourceId, true);
         } else if (newSelected.get(resourceId) === true) {
            newSelected.delete(resourceId);
         }

         selectedRef.current = newSelected;
         return newSelected;
      });
   }, []);

   const onUnselectAll = useCallback(() => {
      setSelected(new Map());
      selectedRef.current = new Map();
   }, []);

   const checkSelected = useCallback((id) => {
      return selectedRef.current.has(id);
   }, []);

   return [onSelect, onUnselectAll, selected, checkSelected];
}
