import { useEffect, useRef } from "react";
import { getCountryBounds } from "../domain/geocoding";

const useMapBounds = (mapRef, country) => {
  const done = useRef(false);

  useEffect(() => {
    if (done.current || country === null || country === undefined) {
      return;
    }

    const moveMap = async () => {
      const bounds = await getCountryBounds(country);
      if (bounds) {
        mapRef.current.fitBounds(bounds);
        mapRef.current.panToBounds(bounds);
        mapRef.current.setZoom(3);
        done.current = true;
      }
    };
    moveMap();
  }, [country, mapRef]);
};

export default useMapBounds;
