<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 './AnimeList.svelte';

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

	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 = (media: Media[], displayUnresolved: boolean) => {
		if (media === undefined) {
			return [];
		}

		const releasingMedia = media.filter(
			(media: Media) => media.status == 'RELEASING' && media.nextAiringEpisode !== null
			/* &&
				(media['mediaListEntry'] || { progress: 0 })['progress'] >=
					($displayNotStarted === 'true' ? 0 : 1) */
		);
		const outdatedMedia = releasingMedia.filter((media: Media) => {
			return (
				(media.nextAiringEpisode || { episode: 0 }).episode - 1 <=
				(media.mediaListEntry || { progress: 0 }).progress
			);
		});
		let finalMedia = outdatedMedia.map((media: Media) => {
			if ((media.nextAiringEpisode || { episode: 0 }).episode - 1 <= 0) {
				media.nextAiringEpisode = { episode: -1 };
			}

			return media;
		});

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

		finalMedia.sort((a: Media, b: Media) => {
			return (
				(a.nextAiringEpisode?.timeUntilAiring || 9999) -
				(b.nextAiringEpisode?.timeUntilAiring || 9999)
			);
		});

		finalMedia = finalMedia.filter((item, index, array) => {
			return (
				array.findIndex((i) => {
					return i.id === item.id;
				}) === index
			);
		});

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

		return finalMedia;
	};
</script>

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