<script lang="ts">
	import { mediaListCollection, Type, type Media } from '$lib/AniList/media';
	import type { UserIdentity, AniListAuthorisation } from '$lib/AniList/identity';
	import { onDestroy, onMount } from 'svelte';
	import anime from '../../../stores/anime';
	import settings from '../../../stores/settings';
	import lastPruneTimes from '../../../stores/lastPruneTimes';
	import AnimeList from './AnimeListTemplate.svelte';
	import type { SubsPlease } from '$lib/subsPlease';
	import { injectAiringTime } from '$lib/Media/Anime/airing';

	export let user: AniListAuthorisation;
	export let identity: UserIdentity;

	let animeLists: Promise<Media[]>;
	let startTime: number;
	let endTime: number;

	const keyCacher = setInterval(() => {
		startTime = performance.now();
		endTime = -1;
		animeLists = mediaListCollection(
			user,
			identity,
			Type.Anime,
			$anime,
			$lastPruneTimes.anime,
			true
		);
	}, $settings.cacheMinutes * 1000 * 60);

	onMount(async () => {
		startTime = performance.now();
		animeLists = mediaListCollection(user, identity, Type.Anime, $anime, $lastPruneTimes.anime);
	});

	onDestroy(() => clearInterval(keyCacher));

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

		let dueAnime = anime
			.filter(
				// Releasing media
				(media: Media) =>
					media.status === 'RELEASING' &&
					(media.mediaListEntry || { status: 'DROPPED' }).status !=
						($settings.displayPausedMedia ? '' : 'PAUSED') &&
					(media.mediaListEntry || { progress: 0 }).progress >=
						($settings.displayNotStarted === true ? 0 : 1)
			)
			.filter(
				(media: Media) =>
					// Outdated media
					(media.nextAiringEpisode || { episode: 0 }).episode - 1 !=
					(media.mediaListEntry || { progress: 0 }).progress
			)
			.map((media: Media) => {
				if ((media.nextAiringEpisode || { episode: 0 }).episode - 1 <= 0)
					media.nextAiringEpisode = { episode: -1 };

				return media;
			})
			.map((media) => injectAiringTime(media, subsPlease));

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

		dueAnime.sort((a: Media, b: Media) => {
			if ($settings.displaySortedByDifference === true) {
				const difference = (anime: Media) =>
					(anime.nextAiringEpisode?.episode === -1
						? 99999
						: anime.nextAiringEpisode?.episode || -1) -
					(anime.mediaListEntry || { progress: 0 }).progress;

				return difference(a) - difference(b);
			} else {
				return (a.nextAiringEpisode?.airingAt || 9999) - (b.nextAiringEpisode?.airingAt || 9999);
			}
		});

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

		return dueAnime;
	};
</script>

<AnimeList {endTime} {cleanMedia} bind:animeLists {user} {identity} title="Anime" />
