import { useMap } from "react-leaflet";

import { useMapSlice } from "../modules/watcher/map/map.slice";
import { useWatcherStore } from "../modules/watcher/store/watcher.store";
import { isNumber } from "../services/math";

export const useMapMover = () => {
	const map = useMap();
	const { assets } = useWatcherStore();
	const { setCurrentPopupObjectId } = useMapSlice();

	return (assetId: string) => {
		const asset = assets.find((x) => x.id === assetId);

		if (!asset) {
			return false;
		}

		const latitude = isNumber(asset.latitude);
		const longitude = isNumber(asset.longitude);

		if (!latitude.is || !longitude.is) {
			return false;
		}

		map.closePopup();
		map.setView([latitude.value, longitude.value], 17, {
			animate: true,
		});

		setCurrentPopupObjectId(asset.id);

		return true;
	};
};
