import { createContext, useCallback, useState } from "react";
import useMap from "../hooks/useMap";

const CreatedLocateCoordinateContext = createContext({
    coordinate: null,
    locateCoordinateHandler: () => {},
    setCoordinate: () => {},
});

const LocateCoordinateContextProvider = ({ children }) => {
    const [coordinate, setCoordinate] = useState(null);
    const { map } = useMap();

    const locateCoordinateHandler = useCallback(
        (coordinate) => {
            setCoordinate(coordinate);

            map.panTo(coordinate);
            map.setZoom(20);
        },
        [setCoordinate, map]
    );

    const locateCoordinateClear = () => {
        setCoordinate(null);
    };

    return (
        <CreatedLocateCoordinateContext.Provider
            value={{
                coordinate,
                locateCoordinateHandler,
                setCoordinate,
                locateCoordinateClear,
            }}
        >
            {children}
        </CreatedLocateCoordinateContext.Provider>
    );
};

export { LocateCoordinateContextProvider, CreatedLocateCoordinateContext };
