<script lang="ts">
	/* eslint svelte/no-at-html-tags: "off" */

	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 { cleanCache, totalEpisodes, updateMedia } from '$lib/Media/anime';

	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 !== 'RELEASING' &&
				media.status !== 'NOT_YET_RELEASED' &&
				(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);
		});

		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>

{#await animeLists}
	<summary>Completed Anime [...] <small style="opacity: 50%">...s</small></summary>

	<ul><li>Loading ...</li></ul>
{:then media}
	{@const cleanedMedia = cleanMedia(media)}

	<summary
		>Completed Anime [{cleanedMedia.length}]
		<small style="opacity: 50%">{endTime / 1000}s</small></summary
	>

	{#if cleanedMedia.length === 0}
		<ul>
			<li>
				No anime to display. <a
					href={'#'}
					on:click={() => (animeLists = cleanCache(user, identity))}>Force refresh</a
				>
			</li>
		</ul>
	{/if}

	<ul>
		{#each cleanedMedia as anime}
			<li>
				<a
					href={$settings.linkToAniList
						? `https://anilist.co/anime/${anime.id}`
						: `https://www.livechart.me/search?q=${
								anime.title.native || anime.title.english || anime.title.romaji
						  }`}
					target="_blank"
				>
					{anime.title.english || anime.title.romaji || anime.title.native}
				</a>
				<span style="opacity: 50%;">|</span>
				{anime.mediaListEntry?.progress || 0}{@html totalEpisodes(anime)}
				<a
					href={'#'}
					on:click={() =>
						updateMedia(
							anime.id,
							anime.mediaListEntry?.progress,
							() => (animeLists = cleanCache(user, identity))
						)}>+</a
				>
			</li>
		{/each}
	</ul>
{:catch}
	<summary>Upcoming Episodes [?] <small style="opacity: 50%">0s</small></summary>

	<ul>
		<li>
			<p>
				Media could not be loaded. You might have been <a
					href="https://en.wikipedia.org/wiki/Rate_limiting"
					target="_blank">rate limited</a
				>.
			</p>
			<p>
				Try again in a few minutes. If the problem persists, please contact
				<a href="https://anilist.co/user/fuwn" target="_blank">@fuwn</a> on AniList.
			</p>
		</li>
	</ul>
{/await}
