<script>
  import { authenticationToken } from "../stores.js";
  import api from "../utilities/api";
  import baseUrl from "../utilities/baseUrl";
  import InfiniteLoading from "svelte-infinite-loading";
  import { format } from "date-fns";

  let tokenValue;
  authenticationToken.subscribe((value) => {
    tokenValue = value;
  });

  let page = 1;
  const size = 10;
  let memes = [];

  function infiniteHandler({ detail: { loaded, complete } }) {
    api()
      .get("/memes", {
        params: {
          page: page,
          per_page: size,
        },
      })
      .then((response) => {
        if (response.data.length) {
          page += 1;
          memes = [...memes, ...response.data];
          loaded();
        } else {
          complete();
        }
      });
  }

  function upvote(meme_id) {
    api()
      .post(`/memes/${meme_id}/votes`)
      .then(() => {
        const memeIndex = memes.findIndex((meme) => meme.id === meme_id);
        memes[memeIndex].voted = true;
        memes[memeIndex].vote_count++;
      });
  }
</script>

<div class="container is-fluid">
  {#each memes as meme, index}
    <div class="columns is-centered">
      <div class="column is-two-thirds" data-num={index + 1}>
        <div class="columns">
          <div class="column is-two-thirds">
            <img src={`${baseUrl}${meme.file_url}`} alt="Meme" />
          </div>

          <div class="column" style="text-align:right;">
            <span class="tag is-black"
              >Hochgeladen am: {format(
                new Date(Date.parse(meme.created_at)),
                "dd.MM.yyyy"
              )}</span
            >

            <br />

            <span class="tag is-link">Slot: {meme.slot}</span>

            <br /><br />

            {#if tokenValue}
              {#if meme.voted}
                <button
                  class="button has-tooltip-bottom has-tooltip-info"
                  data-tooltip="You already voted for this meme!"
                  disabled
                >
                  Upvote ({meme.vote_count})
                </button>
              {:else}
                <button class="button" on:click={() => upvote(meme.id)}>
                  Upvote ({meme.vote_count})
                </button>
              {/if}
            {/if}
          </div>
        </div>
      </div>
    </div>
  {/each}
  <InfiniteLoading on:infinite={infiniteHandler} />

  <br />

  <footer class="footer">
    <div class="content has-text-centered">
      <p>
        <strong>MegaMeme</strong> | Copyright &#169; 2021 by L.Ceriani, A.Pfister
        &#38; M.Brändli
      </p>
    </div>
  </footer>
</div>
