import { useEffect, useRef } from "react";
import { AppState, AppStateStatus } from "react-native";

export const useFetchOnAppForeground = () => {
  const listener = useRef(null);

  function fetchOnAppForeground(params) {
    if (AppState.currentState === "active") {
      return fetch(params);
    } else {
      return new Promise((resolve, reject) => {
        function fetchData(state: AppStateStatus) {
          if (state === "active") {
            console.log("calling foreground fetch");
            fetch(params).then(resolve).catch(reject);
            AppState.removeEventListener("change", fetchData);
            listener.current = null;
          }
        }

        AppState.addEventListener("change", fetchData);
        listener.current = fetchData;
      });
    }
  }

  useEffect(() => {
    return () => {
      if (listener.current) {
        AppState.removeEventListener("change", listener.current);
      }
    };
  }, []);

  return fetchOnAppForeground;
};
