import { useEffect, useRef, useState } from "react";

const useUserActivity = () => {
  //
  const events = useRef([
    "click",
    "mouseup",
    "keydown",
    "scroll",
    "mousemove",
    "touchstart",
    "touchmove",
    "touchend",
    "orientationchange",
    "online",
  ]);

  const [isActiveUser, setIsActiveUser] = useState<boolean>(true);

  const activityResetTime = useRef<NodeJS.Timeout | undefined>(undefined);

  useEffect(() => {
    events.current.forEach(function (e) {
      document.addEventListener(e, function () {
        setIsActiveUser(true);

        if (activityResetTime.current) clearTimeout(activityResetTime.current);
        activityResetTime.current = setTimeout(
          () => {
            setIsActiveUser(false);
          },
          3 * 60 * 1000, //3 minutes
        );
      });
    });
  }, [events, setIsActiveUser]);

  return {
    isUserActiveOnBrowser: isActiveUser,
  };
};

export default useUserActivity;
