import {FetchResult, useAsyncData} from "#app";
import {useImageManager} from "~/composables/data/useImageManager";

interface useImageFetchReturnType {
    fetch: (id: number | null, defaultImage?: string | null, height?: number, width?: number) => FetchResult<any>
}

/**
 * Sert d'intermédiaire entre les composants et l'ImageManager en fournissant une méthode useAsyncData toute prête.
 */
export const useImageFetch = (): useImageFetchReturnType => {
    const { imageManager } = useImageManager()

    const fetch = (
        id: number | null,  // If id is null, fetch shall return the default image url
        defaultImage: string | null = null,
        height: number = 0,
        width: number = 0
    ): FetchResult<string> => useAsyncData(
        'img' + (id ?? defaultImage ?? 0),
        () => imageManager.get(id, defaultImage, height, width),
        { lazy: true, server: false }  // Always fetch images client-side
    )

    return { fetch }
}
