<script module lang="ts">
    import pDebounce from "p-debounce"

    import { apiBaseURL } from "../../configs/config"
    import { getCachedEntries, getCachedEntry } from "../../api"
    const medialibCache: { [id: string]: MedialibEntry } = {}

    let loadQueue: string[] = []
    export async function loadMedialibEntry(id: string): Promise<MedialibEntry> {
        if (medialibCache[id]) return medialibCache[id]
        loadQueue.push(id)
        await processQueueDebounced()
        return medialibCache[id]
    }

    const processQueue = async () => {
        if (loadQueue.length) {
            const _ids = loadQueue
            loadQueue = []
            const entries = await getCachedEntries("medialib", { _id: { $in: _ids } })
            entries.forEach((entry) => {
                medialibCache[entry.id] = entry
            })
        }
    }

    const processQueueDebounced = pDebounce(processQueue, 50)
</script>

<script lang="ts">
    let {
        id,
        noPlaceholder,
        loading,
        childrenSnippet,
        loadingSnippet,
        notFoundSnippet,
    }: {
        id: string
        noPlaceholder?: boolean
        loading?: boolean
        loadingSnippet: ({ entry, src }: { entry: MedialibEntry; src: string }) => any
        childrenSnippet: ({ entry, src }: { entry: MedialibEntry; src: string }) => any
        notFoundSnippet: () => any
    } = $props()

    let entry: MedialibEntry = $state(),
        fileSrc: string = $state()

    async function loadFile() {
        loading = true
        entry = null
        fileSrc = null
        try {
            entry =
                typeof window !== "undefined"
                    ? await loadMedialibEntry(id)
                    : await getCachedEntry("medialib", { _id: id })
            if (entry?.file?.src) {
                fileSrc = `${apiBaseURL}${window?.location.host.includes("tibi") ? "_/renz_shop_2024/" : ""}medialib/${id}/${entry.file.src}`
            }
        } catch (e) {
            console.error(e)
        }
        loading = false
    }

    $effect(() => {
        if (id) loadFile()
    })
</script>

{#if id}
    {#if loading}
        {#if !noPlaceholder}
            {@render loadingSnippet({ entry, src: fileSrc })}
        {/if}
    {:else if entry}
        {@render childrenSnippet({ entry, src: fileSrc })}
    {:else if !noPlaceholder}
        {@render notFoundSnippet()}
    {/if}
{/if}
