<script lang="ts">
	import type { FileTree, File, Folder } from '$lib/types';
	import { metafileSchema } from '$lib/packwiz-types';
	import toml from '@ltd/j-toml';
	import { XIcon } from 'svelte-feather-icons';
	export let tree: Folder;
	function getFilesRecursively(tree: FileTree): [string[], File][] {
		if (tree.type == 'file') {
			return [[[], tree]];
		}
		let result: [string[], File][] = [];
		for (const child in tree.children) {
			if (Object.prototype.hasOwnProperty.call(tree.children, child)) {
				const element = tree.children[child];
				result = result.concat(
					getFilesRecursively(element).map(([path, file]) => [[child].concat(path), file])
				);
			}
		}
		return result;
	}
	function deletePath(path: string[], base: Folder) {
		if (path.length <= 1) {
			delete base.children[path[0]];
		} else {
			const newBase = base.children[path.shift() ?? ''];
			if (newBase.type == 'file') {
				return;
			}
			deletePath(path, newBase);
		}
	}
</script>

<ul>
	{#each getFilesRecursively(tree) as mod (mod[0])}
		<li>
			{#if mod[1].inline && mod[1].metafile}
				{@const parsed = metafileSchema.parse(toml.parse(mod[1].content))}
				<h2>
					{parsed.name} ({mod[0].join('/')})
					<button
						on:click={() => {
							deletePath(mod[0], tree);
							tree = tree;
						}}><XIcon /></button
					>
				</h2>
				{#if parsed.update.curseforge}
					<a
						href="https://minecraft.curseforge.com/projects/{parsed.update.curseforge[
							'project-id'
						]}">Curseforge</a
					>
				{/if}
				{#if parsed.update.modrinth}
					<a href="https://modrinth.com/project/{parsed.update.modrinth['mod-id']}">Modrinth</a>
				{/if}
			{:else}
				<h2>{mod[0].join('/')}</h2>
			{/if}
		</li>
	{/each}
</ul>
