<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 settings from '$stores/settings';
  import AnimeList from './AnimeListTemplate.svelte';
  import { addNotification } from '$lib/Notification/store';
  import locale from '$stores/locale';
  import identity from '$stores/identity';
  import sampleAnime from '$lib/Data/Static/SampleMedia/anime.json';

  export let user: AniListAuthorisation = {
    accessToken: '',
    refreshToken: '',
    expiresIn: 0,
    tokenType: ''
  };
  export let dummy = false;
  export let disableFilter = false;
  let animeLists: Promise<Media[]>;
  let startTime: number;
  let endTime: number;

  onMount(async () => {
    startTime = performance.now();

    if (dummy) {
      animeLists = Promise.resolve(
        sampleAnime
          .filter(
            (anime) =>
              anime.episodes &&
              !anime.tags.some((tag) => tag.name === 'Nudity') &&
              !anime.tags.some((tag) => tag.name === 'Rape') &&
              !anime.tags.some((tag) => tag.name === 'Tragedy') &&
              !anime.tags.some((tag) => tag.name === 'Bondage') &&
              !anime.genres.some((genre) => genre === 'Hentai') &&
              anime.genres.some((genre) => genre === 'Comedy') &&
              anime.status !== 'NOT_YET_RELEASED' &&
              anime.episodes > 1
          )
          .sort(() => 0.5 - Math.random())
          .map((anime) => {
            const nextEpisode = Math.floor(Math.random() * (anime.episodes || 0)) + 1 || 1;

            anime.status = 'FINISHED';
            anime.nextAiringEpisode = {
              airingAt:
                Math.floor(Date.now() / 1000) +
                Math.floor(Math.random() * 7 * 24 * 60 * 60) +
                60 * 60,
              episode: Math.floor(Math.random() * (anime.episodes || 0)) + 1 || 1
            };
            anime.mediaListEntry.progress = Math.floor(Math.random() * nextEpisode) || 1;

            return anime;
          })
          .sort(
            (a, b) => (a.nextAiringEpisode?.airingAt || 0) - (b.nextAiringEpisode?.airingAt || 0)
          )
          .slice(0, 7) as unknown as Media[]
      );
    } else {
      animeLists = mediaListCollection(user, $identity, Type.Anime, $anime, $lastPruneTimes.anime, {
        addNotification
      });
    }
  });

  const cleanMedia = (anime: Media[]) => {
    if (anime && dummy) return anime;

    if (anime === undefined) return [];

    const outdatedCompletedAnime = anime.filter(
      (media: Media) =>
        media.status === 'FINISHED' &&
        (media.mediaListEntry || { status: 'DROPPED' }).status != 'DROPPED' &&
        (media.mediaListEntry || { status: 'DROPPED' }).status !=
          ($settings.displayPausedMedia ? '' : 'PAUSED') &&
        (media.mediaListEntry || { progress: 0 }).progress >= ($settings.displayNotStarted ? 0 : 1)
    );

    outdatedCompletedAnime.sort((a: Media, b: Media) => {
      switch ($settings.displayAnimeSort) {
        case 'difference': {
          const difference = (anime: Media) =>
            (anime.nextAiringEpisode?.episode === -1
              ? 99999
              : anime.nextAiringEpisode?.episode || -1) -
            (anime.mediaListEntry || { progress: 0 }).progress;

          return difference(a) - difference(b);
        }

        case 'end_date':
          return (
            new Date(a.endDate.year, a.endDate.month - 1).getTime() -
            new Date(b.endDate.year, b.endDate.month - 1).getTime()
          );

        case 'start_date':
          return (
            new Date(a.startDate.year, a.startDate.month - 1).getTime() -
            new Date(b.startDate.year, b.startDate.month - 1).getTime()
          );

        case 'time_remaining':
          return (a.nextAiringEpisode?.airingAt || 9999) - (b.nextAiringEpisode?.airingAt || 9999);
      }
    });

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

    return outdatedCompletedAnime;
  };
</script>

<AnimeList
  {endTime}
  {cleanMedia}
  bind:animeLists
  {user}
  title={$locale().lists.completed.anime}
  completed
  {dummy}
  {disableFilter}
/>
