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

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

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

<div class="container is-fluid">
  {#each memes as meme, index}
    <div class="columns is-centered">
      <div class="column is-two-thirds">
        <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"
              >Generated at: {format(
                new Date(Date.parse(meme.created_at)),
                "dd.MM.yyyy"
              )}</span
            >
          </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>
