<script lang="ts">
	import { checkDduf } from '$lib/check-dduf';
	import { tick } from 'svelte';

	let url = $state('https://huggingface.co/DDUF/Flux.1-Dev-Tnf4-TE2NF4/resolve/main/Flux.1-Dev-Tnf4-TE2NF4.dduf');
	let output = $state('');
	let error = $state('');
	let files: Array<{ position: number; size: number; name: string }> = $state([]);

	async function handleSubmit(event: Event) {
		event.preventDefault();
		output = 'Checking...';
		error = '';
		files = [];

		try {
			for await (const file of checkDduf(url, {
				log: (s) => {
					output += '\n' + s;
					tick().then(() => {
						textarea.scrollTop = textarea.scrollHeight;
					});
				}
			})) {
				files.push({
					position: file.fileHeaderOffset,
					size: file.size,
					name: file.name
				});
			}
		} catch (e) {
			console.error(e);
			error = (e as Error).message;
		}
	}

	let textarea: HTMLTextAreaElement;
</script>

<div class="flex flex-col gap-4 p-4">
	<h1 class="text-xl font-bold">DDUF Check</h1>

	<form class="flex flex-col gap-4" onsubmit={handleSubmit}>
		<label class="flex flex-col gap-2">
			DDUF URL (resolved url)
			<input
				type="url"
				name="url"
				placeholder="https://huggingface.co/spaces/coyotte508/dduf-check/resolve/main/file.dduf"
				bind:value={url}
				class="w-full rounded-md border border-gray-300 p-2"
			/>
		</label>

		<button type="submit" class="self-start rounded-md bg-blue-500 p-2 text-white">Check</button>

		<textarea
			bind:this={textarea}
			class="w-full rounded-md border border-gray-300 p-2"
			rows="10"
			readonly>{output}</textarea
		>

		{#if error}
			<p class="text-red-500">{error}</p>
		{/if}

		{#if files.length > 0}
			<h2 class="text-lg font-bold">Files</h2>
			<ul class="ml-4 list-disc">
				{#each files as file}
					<li style="margin-left: {file.name.slice(0, -1).split('/').length - 1}rem">
						{file.name} - {file.size} B
					</li>
				{/each}
			</ul>
		{/if}

		<p>
			To create a zip file with 0 compression you can do <span
				class="rounded-md bg-gray-100 p-1 font-mono">cd folder && zip -r -0 ../file.dduf .</span
			>
		</p>
	</form>
</div>
