<script lang="ts">
import { global_navigator } from "filesystem/FSNavigator";
import { fs_encode_path, fs_node_icon, FSNode } from "lib/FilesystemAPI.svelte";
import { highlight_current_page } from "lib/HighlightCurrentPage";
import { onMount } from "svelte";
import MenuEntry from "./MenuEntry.svelte";

let siblings: FSNode[] = $state([])

onMount(() => {
	return global_navigator.subscribe(async () => {
		const all_siblings = await global_navigator.get_siblings()

		// Find the base
		let base_idx = 0
		for (let i = 0; i < all_siblings.length; i++) {
			if (global_navigator.base.id === all_siblings[i].id) {
				base_idx = i
				break
			}
		}

		siblings = all_siblings.slice(
			Math.max(base_idx-50,0),
			Math.min(base_idx+50, all_siblings.length),
		)
	})
})
</script>

<MenuEntry id="tree_parents">
	{#snippet title()}
		<div class="title">Parent directories</div>
		<button title="Navigate up" onclick={() => global_navigator.navigate_up()} class="button flat">
			<i class="icon">north</i>
		</button>
	{/snippet}

	{#snippet body()}
		{#each $global_navigator.path.slice(0, $global_navigator.path.length-1) as node (node.id)}
			{#if node.type === "dir"}
				<div class="row">
					<a class="button" href="/d{fs_encode_path(node.path)}" title="{node.name}">
						<img class="thumbnail" src="{fs_node_icon(node, 32, 32)}" alt="{node.name}"/>
						<span>{node.name}</span>
					</a>
				</div>
			{/if}
		{/each}
	{/snippet}
</MenuEntry>

<MenuEntry id="tree_siblings">
	{#snippet title()}
		<div class="title">Siblings</div>
	<button title="Open previous sibling" onclick={() => global_navigator.open_sibling(-1)} class="button flat">
		<i class="icon">west</i>
	</button>
	<button title="Open next sibling" onclick={() => global_navigator.open_sibling(1)} class="button flat">
		<i class="icon">east</i>
	</button>
	{/snippet}

	{#snippet body()}
		{#each siblings as node (node.id)}
			{#if !node.is_hidden()}
				<div class="row">
					<a class="button" href="/d{fs_encode_path(node.path)}" title="{node.name}" use:highlight_current_page>
						<img class="thumbnail" src="{fs_node_icon(node, 32, 32)}" alt="{node.name}"/>
						<span>{node.name}</span>
					</a>
				</div>
			{/if}
		{/each}
	{/snippet}
</MenuEntry>

<style>
.title {
	flex: 1 1 auto;
	margin: 3px;
}
.row {
	display: flex;
	flex-direction: row;
}
.row>a {
	flex: 1 1 auto;
}
.row>a>span {
	text-overflow: ellipsis;
	overflow: hidden;
	white-space: nowrap;
}
.button {
	background: none;
	box-shadow: none;
}
.thumbnail {
	height: 1.5em;
	width: 1.5em;
	border-radius: 2px;
}
</style>
