import getConfig from "next/config";
import React from "react";
import { useIFrameWindow } from "../../../FrameContext";
const { publicRuntimeConfig } = getConfig();
export function useMap(config, markerConfig) {
    const ref = React.useRef(null);
    const frame = useIFrameWindow();
    const [marker, setMarker] = React.useState(null);
    const [mapbox, setMapbox] = React.useState(null);
    const [isRealtimePosition, setIsRealtimePosition] = React.useState(false);
    React.useEffect(() => {
        const frameWindow = frame.window || window;
        let _mapbox = null;
        setTimeout(() => {
            if (!frameWindow.mapboxgl ||
                !frameWindow.MapboxGeocoder ||
                !ref.current ||
                !publicRuntimeConfig)
                return;
            frameWindow.mapboxgl.accessToken = publicRuntimeConfig.mapboxToken;
            _mapbox = new frameWindow.mapboxgl.Map(Object.assign({ container: ref.current, style: "mapbox://styles/mapbox/streets-v12", center: (markerConfig === null || markerConfig === void 0 ? void 0 : markerConfig.defaultMarker) || [106.816666, -6.2], projection: {
                    name: "globe",
                }, zoom: 13 }, config));
            setMapbox(_mapbox);
            const _marker = new frameWindow.mapboxgl.Marker();
            setMarker(_marker);
            if (markerConfig === null || markerConfig === void 0 ? void 0 : markerConfig.defaultMarker) {
                _marker.setLngLat(markerConfig.defaultMarker).addTo(_mapbox);
                if (navigator.geolocation) {
                    navigator.geolocation.getCurrentPosition((p) => {
                        setIsRealtimePosition(p.coords.longitude === markerConfig.defaultMarker[0] &&
                            p.coords.latitude === markerConfig.defaultMarker[1]);
                    });
                }
            }
            _mapbox.on("click", (e) => {
                _marker.setLngLat([e.lngLat.lng, e.lngLat.lat]).addTo(_mapbox);
                markerConfig.onMarkerSet({ lng: e.lngLat.lng, lat: e.lngLat.lat });
                if (navigator.geolocation) {
                    navigator.geolocation.getCurrentPosition((p) => {
                        setIsRealtimePosition(p.coords.longitude === e.lngLat.lng &&
                            p.coords.latitude === e.lngLat.lat);
                    });
                }
            });
        }, 500);
        return () => {
            _mapbox === null || _mapbox === void 0 ? void 0 : _mapbox.remove();
            setMarker(null);
            setMapbox(null);
            setIsRealtimePosition(false);
        };
    }, []);
    return { ref, marker, mapbox, isRealtimePosition };
}
//# sourceMappingURL=useMap.js.map