<script lang="ts">
    import MedialibFile from "./MedialibFile.svelte"

    export let id: string,
        filter: null | "xs" | "s" | "m" | "l" | "xl" | "xxl" = null,
        minWidth: number = null,
        noPlaceholder: boolean = false

    let imgElement: HTMLImageElement

    function getSrcWithFilter(_imgElement: HTMLImageElement, entry: MedialibEntry, src: string) {
        if (typeof window === "undefined") {
            return src + `?filter=${filter || "xs"}`
        }
        if (imgElement) {
            if (!entry.file?.type?.match(/^image\/(png|jpe?g)/)) return src // no filter for svg
            if (!filter) {
                // get the width of the image element
                const width = minWidth
                    ? _imgElement.width < minWidth
                        ? minWidth
                        : _imgElement.width
                    : _imgElement.width
                switch (true) {
                    case width <= 90:
                        filter = "xs"
                        break
                    case width <= 300:
                        filter = "s"
                        break
                    case width <= 600:
                        filter = "m"
                        break
                    case width <= 1200:
                        filter = "l"
                        break
                    case width <= 2000:
                        filter = "xl"
                        break
                    case width <= 4000:
                        filter = "xxl"
                        break
                }
            }
            return src + (filter ? `?filter=${filter}` : "")
        } else {
            // placeholder
            return "/assets/img/placeholder-image.png"
        }
    }
</script>

{#if id}
    <MedialibFile
        id={id}
        let:entry
        let:src
        noPlaceholder={noPlaceholder}
    >
        <img
            bind:this={imgElement}
            src={getSrcWithFilter(imgElement, entry, src)}
            alt={entry.alt || 'icon'}
            data-entry-id={id}
        />
        <img
            slot="loading"
            let:entry
            let:src
            src="/assets/img/placeholder-image.png"
            alt="placeholder"
            data-entry-id={id}
            data-entry={JSON.stringify(entry)}
            data-entry-src={src}
        />
        <img
            slot="not-found"
            src="/assets/img/placeholder-image.png"
            alt="not found"
            data-entry-id={id}
        />
    </MedialibFile>
{/if}
