<script lang="ts">
  import Message from '$lib/Loading/Message.svelte';
  import root from '$lib/Utility/root';
  import type { Live, ParseResult } from './hololive';
  import Stream from './Stream.svelte';

  export let schedule: ParseResult;
  export let pinnedStreams: string[];
  export let getPinnedStreams: () => void;
  export let filter: string | undefined;

  const pinStream = (streamer: string) =>
    fetch(root(`/api/preferences/pin?stream=${encodeURIComponent(streamer)}`), {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      }
    }).then(getPinnedStreams);

  $: categorisedStreams = schedule.lives
    .filter((live) => (filter ? live.streamer === filter : true))
    .sort((a, b) => new Date(a.time).getTime() - new Date(b.time).getTime())
    .sort((a, b) => {
      const aPinned = pinnedStreams.includes(a.streamer);
      const bPinned = pinnedStreams.includes(b.streamer);

      if (aPinned && !bPinned) return -1;
      if (!aPinned && bPinned) return 1;

      return 0;
    })
    .reduce(
      (
        acc: {
          live: Live[];
          upcoming: Live[];
          ended: Live[];
        },
        live
      ) => {
        const now = Date.now();
        const time = new Date(live.time).getTime();
        const isLive = live.streaming;
        const isUpcoming = time > now && !isLive;
        const isEnded = time < now && !isLive;

        if (isLive) {
          acc.live.push(live);
        } else if (isUpcoming) {
          acc.upcoming.push(live);
        } else if (isEnded) {
          acc.ended.push(live);
        }

        return acc;
      },
      { live: [], upcoming: [], ended: [] }
    );
</script>

{#if schedule.lives.length === 0}
  <Message message="No upcoming streams." loader="ripple" />
{/if}

<div class="container">
  {#each categorisedStreams.live as live}
    <Stream {live} {pinStream} {pinnedStreams} icon={schedule.dict[live.streamer]} />
  {/each}
</div>

<p></p>

<div class="container">
  {#each categorisedStreams.upcoming as live}
    <Stream {live} {pinStream} {pinnedStreams} icon={schedule.dict[live.streamer]} />
  {/each}
</div>

<p></p>

<div class="container">
  {#each categorisedStreams.ended as live}
    <Stream {live} {pinStream} {pinnedStreams} icon={schedule.dict[live.streamer]} />
  {/each}
</div>

<style lang="scss">
  .container {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(22em, 1fr));
    gap: 0.5em;
  }
</style>
