<script lang="ts">
	import {
		activityHistory,
		fillMissingDays,
		type ActivityHistoryEntry
	} from '$lib/AniList/activity';
	import { onMount } from 'svelte';
	import userIdentity from '$stores/identity';
	import type { AniListAuthorisation } from '$lib/AniList/identity';
	import { clearAllParameters } from '../../Utility/parameters';
	import { domToBlob } from 'modern-screenshot';
	import ActivityHistoryGrid from './Grid.svelte';
	import SettingHint from '$lib/Settings/SettingHint.svelte';
	import Skeleton from '$lib/Loading/Skeleton.svelte';

	export let user: AniListAuthorisation;

	let activityHistoryData: Promise<ActivityHistoryEntry[]>;
	let generated = false;

	onMount(async () => {
		clearAllParameters();

		if (user !== undefined) activityHistoryData = activityHistory($userIdentity);
	});

	// const incrementDate = (date: Date): Date => {
	// 	date.setDate(date.getDate() + 1);

	// 	return date;
	// };

	const screenshot = async () => {
		let element = document.querySelector('.grid') as HTMLElement;

		if (element !== null) {
			domToBlob(element, {
				quality: 1,
				scale: 2
			}).then((blob) => {
				const downloadWrapper = document.createElement('a');
				const image = document.createElement('img');
				const object = (window.URL || window.webkitURL || window || {}).createObjectURL(blob);

				downloadWrapper.href = object;
				downloadWrapper.target = '_blank';
				image.src = object;

				downloadWrapper.appendChild(image);

				const gridFinal = document.getElementById('grid-final');

				if (gridFinal !== null) {
					gridFinal.innerHTML = '';

					gridFinal.appendChild(downloadWrapper);

					generated = true;
				}

				downloadWrapper.click();
			});
		}
	};
</script>

{#if user === undefined}
	<div class="card popup">Please log in to view this page.</div>
{:else}
	{#await activityHistoryData}
		<Skeleton card={false} count={5} height="0.9rem" list />
	{:then activities}
		{#if activities === undefined}
			<Skeleton card={false} count={5} height="0.9rem" list />
		{:else}
			{@const filledActivities = fillMissingDays(activities)}

			<div class="card">
				<ActivityHistoryGrid {user} />

				<p />

				<div id="grid-final" />

				{#if generated}
					<p />
				{/if}

				<button on:click={screenshot}>Generate grid image</button>
			</div>

			<p />

			<details open>
				<summary>Days in risk of developing an activity history hole</summary>

				<SettingHint>
					Days in which you did not log any activity or only have one activity logged.
				</SettingHint>

				<ul>
					{#each filledActivities as activity}
						{#if activity.amount === 0}
							<li>
								{new Date(
									activity.date * 1000 + new Date().getTimezoneOffset() * 60 * 1000
								).toDateString()}
							</li>
						{/if}
					{/each}
				</ul>
			</details>
		{/if}
	{/await}
{/if}
