<script lang="ts">
	import { mediaListCollection, Type, type Media } from '$lib/AniList/media';
	import type { UserIdentity, AniListAuthorisation } from '$lib/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';

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

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

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

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

		const filterAnime = (status: 'RELEASING' | 'NOT_YET_RELEASED') =>
			anime
				.filter((media: Media) => media.status === status && media.nextAiringEpisode !== null)
				.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?.timeUntilAiring || 9999) -
				(b.nextAiringEpisode?.timeUntilAiring || 9999)
		);

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

		return upcomingAnime;
	};
</script>

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

{#if $settings.displayPlannedAnime}
	<AnimeList
		{endTime}
		{cleanMedia}
		bind:animeLists
		{user}
		{identity}
		title="Upcoming Episodes (Not Yet Released)"
		plannedOnly
	/>
{/if}
