import { useRef, useEffect, useState } from 'react';
import olMap from 'ol/Map';
import olView from 'ol/View';
import { fromLonLat } from 'ol/proj';

export default function useMap({center, zoom, maxZoom, onInit}) {

    const mapRef = useRef(null);
    const [map, setMap] = useState(null);
    
    useEffect(() => {
        if (mapRef.current && !map) {

            let view = new olView({
                center: fromLonLat(center),
                minZoom: 0,
                maxZoom: maxZoom,
                zoom: zoom
            });
            
            let options = {
                view: view,
                layers: [],
                controls: [],
                overlays: []
            };

            const mapObject = new olMap(options);
            mapObject.setTarget(mapRef.current);
            setMap(mapObject);
            onInit(mapObject);
        }

    }, [mapRef, center, zoom, maxZoom, map, onInit]);

    return { mapRef, map };
};