import { useEffect, useRef } from 'react';

export function useListener<T>(): any {
   const id = useRef<number>(0);
   const events = useRef<Map<number, (resolves: { [key: string]: any }) => void>>(new Map());

   function addEventListener(fn: (resolves: { [key: string]: any }) => void): () => void {
      id.current += 1;
      const currentId = id.current;
      events.current.set(currentId, fn);

      return () => {
         events.current.delete(currentId);
      };
   }

   useEffect(() => {
      return () => {
         events.current.clear();
      };
   }, []);

   function setValue(v: T): void {
      Array.from(events.current.values()).forEach((fn) => fn(v));
   }

   return [addEventListener, setValue];
}
