<script lang="ts">
import EditWindow from "filesystem/edit_window/EditWindow.svelte";
import type { FSNavigator } from "filesystem/FSNavigator";
import Button from "layout/Button.svelte";
import Dialog from "layout/Dialog.svelte";
import { bookmark_add, bookmark_del, bookmarks_store, is_bookmark } from "lib/Bookmarks";
import { fs_trash, type FSNode } from "lib/FilesystemAPI.svelte";
import { loading_finish, loading_start } from "lib/Loading";
import { tick } from "svelte";

let {
	nav,
	edit_window = null
}: {
	nav: FSNavigator;
	edit_window?: EditWindow;
} = $props();

let dialog: Dialog = $state()
let node: FSNode = $state(null)

export const open = async (n: FSNode, target: EventTarget, event: Event) => {
	event.preventDefault()
	event.stopPropagation()

	node = n
	// Wait for the view to update, so the dialog gets the proper measurements
	await tick()

	let el: HTMLElement = (target as Element).closest("button")
	if (el !== null) {
		dialog.open(el.getBoundingClientRect())
		return
	}

	if (event instanceof MouseEvent) {
		dialog.open(event)
		return
	}

	console.error("Cannot find suitable target for spawning dialog window")
}

const delete_node = async () => {
	try {
		loading_start()
		await fs_trash(node.path)
		nav.reload()
	} catch (err) {
		alert(JSON.stringify(err))
	} finally {
		loading_finish()
	}
}
</script>

<Dialog bind:this={dialog}>
	<div class="menu">
		<Button click={() => {dialog.close(); node.download()}} icon="save" label="Download"/>
		{#if node !== null && is_bookmark($bookmarks_store, node.id)}
			<Button click={() => {dialog.close(); bookmark_del(node.id)}} icon="bookmark_remove" label="Remove bookmark"/>
		{:else}
			<Button click={() => {dialog.close(); bookmark_add(node)}} icon="bookmark_add" label="Add bookmark"/>
		{/if}
		{#if $nav.permissions.write}
			<Button click={() => {dialog.close(); delete_node()}} icon="delete" label="Delete"/>
			{#if edit_window !== null}
				<Button click={() => {dialog.close(); edit_window.edit(node, false, "file")}} icon="edit" label="Edit"/>
				<Button click={() => {dialog.close(); edit_window.edit(node, false, "share")}} icon="share" label="Share"/>
				<Button click={() => {dialog.close(); edit_window.edit(node, false, "branding")}} icon="palette" label="Branding"/>
			{/if}
		{/if}
	</div>
</Dialog>

<style>
.menu {
	display: flex;
	flex-direction: column;
	max-width: 20em;
}
</style>
