<script lang="ts">
  import * as api from "$lib/api";

  let fetchData = api.fetchData();
  let listingIndex = 0;

  function updateListingIndex(amount: number): void {
    if (listingIndex >= amount - 1) {
      listingIndex = 0;
      fetchData = api.fetchData();
    } else {
      listingIndex++;
    }
  }

  function handleTime(time: number, listingsAmount: number): void {
    setTimeout(() => updateListingIndex(listingsAmount), time * 1000);
  }

  function handleVideoLoad(
    time: number | undefined,
    listingsAmount: number
  ): void {
    if (time) {
      handleTime(time, listingsAmount);
    }
  }
</script>

{#await fetchData}
  <p>Loading...</p>
{:then data}
  <div class="brett center-box">
    <div class="center">
      {#if data.listings[listingIndex].type == api.ListingType.IMAGE}
        <img
          class="dynamic-size"
          src={api.generateContentURL(data.listings[listingIndex].content)}
          alt={data.listings[listingIndex].name}
          width="100%"
          on:load={() =>
            handleTime(
              data.listings[listingIndex].time || 10,
              data.listings.length
            )}
        />
      {:else if data.listings[listingIndex].type == api.ListingType.VIDEO}
        <video
          class="dynamic-size"
          autoplay
          playsinline
          on:load={() =>
            handleVideoLoad(
              data.listings[listingIndex].time,
              data.listings.length
            )}
          on:ended={() => updateListingIndex(data.listings.length)}
        >
          <source
            src={api.generateContentURL(data.listings[listingIndex].content)}
          />
          <track kind="captions" />
          <b class="error">Videos are not supported!</b>
        </video>
      {/if}
    </div>

    <div class="banner">
      <span class="banner-pre">Powered by </span>
      <a class="banner-name" href="https://dergrimm.net" target="_blank">
        <code>Dominic Grimm &lt;dominic@dergrimm.net&gt;</code>
      </a>
    </div>
  </div>
{:catch error}
  <p><b class="error">An error occured! {error}</b></p>
{/await}

<style lang="scss">
  .brett {
    cursor: none;
    width: 100vw;
    height: 100vh;
    background-color: black;

    * {
      pointer-events: none;
    }
  }

  .banner {
    position: absolute;
    transform: scale(-1);
    writing-mode: vertical-rl;
    right: 1vh;
    bottom: 1vh;
    color: black;
    font-family: "Fira Code";
    background-color: white;
    opacity: 90%;
  }

  .banner-pre {
    // opacity: 30%;
    font-size: small;
  }

  .banner-name {
    // opacity: 70%;
    font-size: large;
    color: blue;
    text-decoration: underline;
  }

  .center-box {
    width: 100%;
    height: 100vh;
    display: flex;
    justify-content: center;
  }

  .center {
    display: flex;
    justify-content: center;
  }

  .dynamic-size {
    max-height: 100vh;
    width: auto;
  }
</style>
