<script lang="ts">
  import { useEntity } from "../../lib/entity";
  import Spinner from "../utils/Spinner.svelte";
  import ModelViewer from "./blobs/ModelViewer.svelte";
  export let address: string;

  $: ({ entity } = useEntity(address));

  $: mimeType = String($entity?.get("FILE_MIME"));
  $: handled =
    Boolean(mimeType) &&
    ["audio", "video", "image", "model", "text"].some((prefix) =>
      mimeType.startsWith(prefix)
    );

  $: textThumbnail = mimeType.startsWith("text")
    ? (async () => {
        const response = await fetch(`/api/thumb/${address}`);
        return await response.text();
      })()
    : null;
</script>

{#if handled}
  <div class="preview">
    {#if mimeType?.startsWith("text")}
      <div class="text">
        {#await textThumbnail}
          <Spinner />
        {:then text}
          {text}
        {/await}
      </div>
    {/if}
    {#if mimeType?.startsWith("audio")}
      <audio controls preload="auto" src="/api/raw/{address}" />
    {/if}
    {#if mimeType?.startsWith("video")}
      <!-- svelte-ignore a11y-media-has-caption -->
      <video
        controls
        preload="auto"
        src="/api/raw/{address}"
        poster="/api/thumb/{address}"
      />
    {/if}
    {#if mimeType?.startsWith("image")}
      <a target="_blank" href="/api/raw/{address}">
        <img src="/api/raw/{address}" alt={address} />
      </a>
    {/if}
    {#if mimeType?.startsWith("model")}
      <ModelViewer src="/api/raw/{address}" />
    {/if}
  </div>
{/if}

<style scoped lang="scss">
  .preview {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  audio,
  video,
  img,
  .text {
    width: 100%;
    max-height: 25em;
  }

  video {
    background: rgba(128, 128, 128, 128);
  }

  .text {
    background: var(--background);
    padding: 0.5em;
    overflow: auto;
    white-space: pre-wrap;
    border-radius: 4px;
    border: 1px solid var(--foreground);
  }
</style>
