<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 { getNotificationsContext } from 'svelte-notifications';
	import locale from '$stores/locale';
	import identity from '$stores/identity';

	export let user: AniListAuthorisation;

	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
		});
	});

	const cleanMedia = (anime: Media[]) => {
		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) => {
			const difference = (anime: Media) =>
				anime.episodes - (anime.mediaListEntry || { progress: 0 }).progress;

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

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

		return outdatedCompletedAnime;
	};
</script>

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