<script lang="ts">
  import { mediaListCollection, Type, type Media } from '$lib/Data/AniList/media';
  import type { AniListAuthorisation } from '$lib/Data/AniList/identity';
  import { onMount } from 'svelte';
  import anime from '$stores/anime';
  import lastPruneTimes from '$stores/lastPruneTimes';
  import AnimeList from './AnimeListTemplate.svelte';
  import settings from '$stores/settings';
  import type { SubsPlease } from '$lib/Media/Anime/Airing/Subtitled/subsPlease';
  import { getNotificationsContext } from 'svelte-notifications';
  import locale from '$stores/locale';
  import identity from '$stores/identity';
  import { injectAiringTime } from '$lib/Media/Anime/Airing/Subtitled/match';
  import revalidateAnime from '$stores/revalidateAnime';

  export let user: AniListAuthorisation;

  const { addNotification } = getNotificationsContext();
  let animeLists: Promise<Media[]>;
  let startTime: number;
  let endTime: number;

  onMount(async () => {
    startTime = performance.now();
    animeLists = mediaListCollection(user, $identity, Type.Anime, $anime, $lastPruneTimes.anime, {
      addNotification,
      notificationType: 'Upcoming Episodes'
    });
  });

  const cleanMedia = (
    anime: Media[],
    displayUnresolved: boolean,
    subsPlease: SubsPlease | null,
    plannedOnly = true
  ) => {
    if (anime === undefined) return [];

    const filterAnime = (status: 'RELEASING' | 'NOT_YET_RELEASED') =>
      anime
        .filter((media: Media) => media.status === status && media.nextAiringEpisode !== null)
        .map((media) => injectAiringTime(media, subsPlease))
        .filter(
          (media: Media) =>
            // Outdated media
            ($settings.displayPlannedAnime ? media.mediaListEntry?.status === 'PLANNING' : false) ||
            (media.nextAiringEpisode || { episode: 0 }).episode - 1 <=
              (media.mediaListEntry || { progress: 0 }).progress
        )
        .map((media: Media) => {
          // Adjust for planned anime
          if (
            ($settings.displayPlannedAnime ? media.episodes !== 1 : true) &&
            (media.nextAiringEpisode || { episode: 0 }).episode - 1 <= 0
          )
            media.nextAiringEpisode = { episode: -1 };

          return media;
        });
    let upcomingAnime = filterAnime(plannedOnly ? 'NOT_YET_RELEASED' : 'RELEASING');

    if (!displayUnresolved)
      upcomingAnime = upcomingAnime.filter(
        (media: Media) => media.nextAiringEpisode?.episode !== -1
      );

    upcomingAnime.sort(
      (a: Media, b: Media) =>
        (a.nextAiringEpisode?.airingAt || 9999) - (b.nextAiringEpisode?.airingAt || 9999)
    );

    if (!endTime) endTime = performance.now() - startTime;

    return upcomingAnime;
  };

  $: {
    if ($revalidateAnime) {
      $revalidateAnime = false;
      $lastPruneTimes.anime = -1;
      animeLists = mediaListCollection(user, $identity, Type.Anime, $anime, $lastPruneTimes.anime, {
        addNotification,
        notificationType: 'Upcoming Episodes'
      });
    }
  }
</script>

<AnimeList
  {endTime}
  {cleanMedia}
  bind:animeLists
  {user}
  title={$locale().lists.upcoming.episodes}
  upcoming
/>

{#if $settings.displayPlannedAnime}
  <p></p>

  <AnimeList
    {endTime}
    {cleanMedia}
    bind:animeLists
    {user}
    title={$locale().lists.upcoming.notYetReleased}
    notYetReleased
    plannedOnly
  />
{/if}
