<script lang="ts">
	import type { PageData } from './$types';
	import { fade } from 'svelte/transition';
	import { invalidateAll } from '$app/navigation';
	import StartScrapeForm from '$lib/StartScrapeForm.svelte';
	import ScrapeJobResult from '$lib/ScrapeJobResult.svelte';

	export let data: PageData;

	$: completedJobs = data.jobs.filter(({ completedTs }) => completedTs !== null);
	$: activeJobs = data.jobs.filter(({ completedTs }) => completedTs === null);
	$: activeJobCount = activeJobs.length;
	$: completedJobCount = completedJobs.length;

	async function onScrape({ detail }) {
		try {
			const response = await fetch(
				new Request('/api/v1/sync', {
					method: 'PUT',
					headers: {
						'Content-Type': 'application/json'
					},
					body: JSON.stringify({ targetSite: detail.target })
				})
			);

			const scrapeJob = await response.json();
			data.jobs.push(scrapeJob);
			console.log(scrapeJob);
		} catch (error) {}
	}
</script>

<section class="flex w-full flex-col justify-center" in:fade out:fade>
	<h1 class="text-2xl mb-8">Sync Status</h1>
	<div class="mb-8">
		<StartScrapeForm on:scrape={onScrape} />
	</div>
	<section>
		<h2>{activeJobCount} In Progress Jobs</h2>
		<ul class="flex">
			{#each activeJobs as j, i}
				<li in:fade>
					<ScrapeJobResult job={j} />
				</li>
				<!-- {#if i < 10}
				{/if} -->
			{/each}
		</ul>
		<h2>{completedJobCount} Complete</h2>
		<ul class="flex flex-wrap justify-between">
			{#each completedJobs as j, i}
				<li in:fade>
					<ScrapeJobResult job={j} />
				</li>
				<!-- {#if i < 5}
				{/if} -->
			{/each}
		</ul>
	</section>
</section>
