var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { useQuery } from "@tanstack/react-query";
import errorTracker from "~/utils/errorTracker";
import { useStateManagerContext } from "~/context/stateManager";
const MAPBOX_DIRECTIONS_ENDPOINT = `${import.meta.env.VITE_PROVIDERS_ENDPOINT}/v1/directions`;
export function useCommute({ mode = "walking", origin, destination, label, locale = "en", units = "metric", }) {
    const { sdkState } = useStateManagerContext();
    /**
     * Fetches a route from Mapbox Directions API.
     *
     * @returns CommuteData | null
     */
    const fetchRoutes = () => __awaiter(this, void 0, void 0, function* () {
        if (!(origin === null || origin === void 0 ? void 0 : origin.lat) || !origin.lng || !(destination === null || destination === void 0 ? void 0 : destination.lat) || !destination.lng) {
            return null;
        }
        let travelMode = "walking";
        if (mode === "driving") {
            travelMode = "driving";
        }
        else if (mode === "cycling") {
            travelMode = "cycling";
        }
        return fetch(`${MAPBOX_DIRECTIONS_ENDPOINT}/${travelMode}/${origin.lng},${origin.lat};${destination.lng},${destination.lat}?geometries=geojson`, {
            headers: {
                Accept: "application/json",
                Authorization: `${sdkState.apiKey}`,
            },
            method: "GET",
        })
            .then((response) => response.json())
            .then((response) => {
            var _a, _b, _c;
            if (((_b = (_a = response.data) === null || _a === void 0 ? void 0 : _a.routes) !== null && _b !== void 0 ? _b : []).length > 0 &&
                ((_c = response.data) === null || _c === void 0 ? void 0 : _c.code) === "Ok") {
                return {
                    mode: travelMode,
                    distance: response.data.routes[0].distance,
                    duration: response.data.routes[0].duration,
                    label,
                    // Convert coordinates from [lng, lat] to [lat, lng]
                    geometry: response.data.routes[0].geometry.coordinates.map((coord) => [coord[1], coord[0]]),
                    destination: {
                        lat: destination.lat,
                        lng: destination.lng,
                    },
                };
            }
            return null;
        })
            .catch((error) => {
            errorTracker.captureException(error);
            throw error;
        });
    });
    return useQuery({
        queryKey: [
            "commute",
            mode,
            origin === null || origin === void 0 ? void 0 : origin.lat,
            origin === null || origin === void 0 ? void 0 : origin.lng,
            destination === null || destination === void 0 ? void 0 : destination.lat,
            destination === null || destination === void 0 ? void 0 : destination.lng,
            locale,
            units,
            label,
        ],
        queryFn: fetchRoutes,
        enabled: !!(origin === null || origin === void 0 ? void 0 : origin.lat) &&
            !!(origin === null || origin === void 0 ? void 0 : origin.lng) &&
            !!(destination === null || destination === void 0 ? void 0 : destination.lat) &&
            !!(destination === null || destination === void 0 ? void 0 : destination.lng),
    });
}
//# sourceMappingURL=index.js.map