import { useEffect, useState } from "react";
import { useDataContext } from "../../common/contexts/data_context"
import { useGet } from "../../common/hooks/useGet";
import { useDownloadFile } from "../../common/hooks/useDownloadFile";
import { ApiRequestStatus } from "../../common/const/api_request_states";
import { router } from "expo-router";

interface UseGetTravelImageProps {
    id: number
}

export const useGetTravelImage = ({ id }: UseGetTravelImageProps) => {
    const { travelRepository } = useDataContext();
    const { handleDownload, saveFileStatus } = useDownloadFile();

    const callback = async () => {
        return await travelRepository!.getVisitImage(id);
    }
    const { requestStatus: getImageStatus, data } = useGet<string>(callback);
    const [requestStatus, setRequestStatus] = useState(ApiRequestStatus.IDLE);

    useEffect(() => {
        const requests = [getImageStatus, saveFileStatus];
        console.log("Requests: "+requests);
        if (requests.some(status => status === ApiRequestStatus.LOADING)) {
            setRequestStatus(ApiRequestStatus.LOADING);
        } else if (requests.some(status => status === ApiRequestStatus.ERROR)) {
            console.log("Error saving image");
            router.push("travel_history/error/save_travel_image_error");
        } else if (requests.every(status => status === ApiRequestStatus.SUCCESS)) {
            //TODO: Show success message
            router.dismissAll();
        } else if (requests.some(status => status === ApiRequestStatus.IDLE || status === ApiRequestStatus.SUCCESS)) {
            setRequestStatus(ApiRequestStatus.SUCCESS);
        }
    }, [getImageStatus, saveFileStatus]);

    return { requestStatus, data, handleDownload };
}