<script lang="ts">
  import { useEntity } from "../../lib/entity";
  import Spinner from "../utils/Spinner.svelte";
  import AudioViewer from "./blobs/AudioViewer.svelte";
  import FragmentViewer from "./blobs/FragmentViewer.svelte";
  import ImageViewer from "./blobs/ImageViewer.svelte";
  import ModelViewer from "./blobs/ModelViewer.svelte";
  import TextViewer from "./blobs/TextViewer.svelte";
  import VideoViewer from "./blobs/VideoViewer.svelte";
  import UpLink from "./UpLink.svelte";
  import api from "../../lib/api";
  import { createEventDispatcher } from "svelte";
  import { getTypes } from "../../util/mediatypes";
  const dispatch = createEventDispatcher();

  export let address: string;
  export let editable: boolean;
  export let detail: boolean;

  let handled = false;

  $: ({ entity, entityInfo } = useEntity(address));
  $: types = $entity && getTypes($entity, $entityInfo);

  $: handled =
    types &&
    (types.audio ||
      types.video ||
      types.image ||
      types.text ||
      types.pdf ||
      types.model ||
      types.web ||
      types.fragment);

  $: dispatch("handled", handled);

  let imageLoaded = null;
</script>

{#if handled}
  <div class="preview" class:detail>
    {#if types.text}
      <div class="text-viewer">
        <TextViewer {address} />
      </div>
    {/if}
    {#if types.audio}
      <AudioViewer {address} {detail} {editable} />
    {/if}
    {#if types.video}
      <VideoViewer detail {address} />
    {/if}
    {#if types.image}
      <ImageViewer {address} {editable} {detail} />
    {/if}
    {#if types.pdf}
      <iframe
        src="{api.apiUrl}/raw/{address}?inline"
        title="PDF document of {address}"
      />
    {/if}
    {#if types.model}
      <ModelViewer src="{api.apiUrl}/raw/{address}" />
    {/if}
    {#if types.web}
      {#if imageLoaded != address}
        <Spinner />
      {/if}
      <img
        src={String($entity?.get("OG_IMAGE"))}
        alt="OpenGraph image for {$entityInfo?.t == 'Url' && $entityInfo?.c}"
        on:load={() => (imageLoaded = address)}
        on:error={() => (handled = false)}
      />
    {/if}
    {#if types.fragment}
      <UpLink passthrough to={{ entity: String($entity.get("ANNOTATES")) }}>
        <FragmentViewer {address} {detail} />
      </UpLink>
    {/if}
  </div>
{/if}

<style scoped lang="scss">
  .preview {
    display: flex;
    align-items: center;
    flex-direction: column;
    // min-height: 33vh;
    max-height: 50vh;

    &.detail {
      height: 100%;
      max-height: 100%;
      flex-grow: 1;
      // min-height: 0;
    }
  }

  img,
  .text-viewer {
    width: 100%;
    max-height: 100%;
  }

  iframe {
    width: 99%;
    flex-grow: 1;
  }

  .text-viewer {
    display: flex;
    margin-bottom: 2rem;
    min-height: 0;
  }

  img {
    object-fit: contain;
  }
</style>
