<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';
	import type { SubsPlease } from '$lib/Media/Anime/Airing/Subtitled/subsPlease';
	import { getNotificationsContext } from 'svelte-notifications';
	import locale from '$stores/locale';

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

	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) =>
						// airedButNotSubtitled(injectAiringTime(media, subsPlease)) ||
						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?.airingAt || 9999) - (b.nextAiringEpisode?.airingAt || 9999)
		);

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

		return upcomingAnime;
	};
</script>

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

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

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