<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 settings from '../../../stores/settings';
	import AnimeList from '../Template/AnimeListTemplate.svelte';

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

		const releasingMedia = media.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)
		);
		let finalMedia = releasingMedia;

		finalMedia.sort((a: Media, b: Media) => {
			const difference = (anime: Media) => {
				return anime.episodes - (anime.mediaListEntry || { progress: 0 }).progress;
			};

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

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

		return finalMedia;
	};
</script>

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