<script lang="ts">
	import type { PageData } from './$types';
	import StartScrapeForm from '$lib/StartScrapeForm.svelte';
	import ScrapeJobResult from '$lib/ScrapeJobResult.svelte';
	import Pager from '$lib/Pager.svelte';

	import { fade } from 'svelte/transition';
	import { onDestroy, onMount } from 'svelte';
	import { invalidateAll } from '$app/navigation';
	import { getSession } from '$lib/state';

	export let data: PageData;

	$: activeJobCount = data.active.length;

	let disableSync = false;

	var intervalId: any;
	onMount(() => {
		intervalId = setInterval(invalidateAll, 2000);
	});
	onDestroy(() => clearInterval(intervalId));

	async function onScrape({ detail }) {
		disableSync = true;
		try {
			const response = await fetch(
				new Request('/api/v1/sync', {
					method: 'PUT',
					headers: {
						'Content-Type': 'application/json',
						'bh-session-id': getSession()?.sessionId
					},
					body: JSON.stringify({ targetSite: detail.target })
				})
			);
		} catch (error) {
		} finally {
			disableSync = false;
		}
	}

	function buildQueryString({ page, pageSize }: { page: number; pageSize: number }): string {
		const qs = [
			data.query === '' ? data.query : `query=${data.query}`,
			page <= 1 ? '' : `page=${page}`,
			`limit=${pageSize}`
		]
			.filter((x) => x !== '')
			.join('&');

		return qs !== '' ? `/?${qs}` : qs;
	}

	const limit = 16;
</script>

<section class="flex w-full flex-col justify-center" in:fade out:fade>
	<section in:fade>
		<h1 class="text-2xl pb-5">Sync Status: {data.total} jobs</h1>
	</section>
	<section class="pb-5">
		<h2 class="text-2xl">{activeJobCount} In Progress</h2>
		{#key data.activeTotal}
			<ul class="flex">
				{#each data.active as job, i}
					<li id="job-{job.id}" in:fade={{ delay: i * 90 }}>
						<ScrapeJobResult {job} />
					</li>
				{/each}
			</ul>
		{/key}
	</section>
	<StartScrapeForm on:scrape={onScrape} disable={disableSync} />
	<section class="py-10">
		<h2 class="text-2xl">Completed</h2>
		<Pager
			page={data.page}
			itemCount={data.completeTotal}
			pageSize={limit}
			createUrl={buildQueryString}
		/>
		{#key data.completeTotal + data.page}
			<ul class="flex flex-wrap justify-between">
				{#each data.complete as job, i}
					<li id="job-{job.id}" in:fade={{ delay: i * 90 }}>
						<ScrapeJobResult {job} />
					</li>
				{/each}
			</ul>
		{/key}
	</section>
	<section>
		<Pager page={data.page} itemCount={data.total} pageSize={limit} createUrl={buildQueryString} />
	</section>
</section>
