<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 } from "lib/Bookmarks";
import { fs_download, type FSNode } from "lib/FilesystemAPI";
import { tick } from "svelte";

export let nav: FSNavigator
export let edit_window: EditWindow
let dialog: Dialog
let node: FSNode
let is_bookmark: boolean = false

export const open = async (n: FSNode, target: EventTarget) => {
	node = n

	is_bookmark = false
	for (const bm of $bookmarks_store) {
		console.log(bm)
		if (bm.id === n.id) {
			is_bookmark = true
			break
		}
	}

	// Wait for the view to update, so the dialog gets the proper measurements
	await tick()
	dialog.open((target as Element).closest("button").getBoundingClientRect())
}

const bookmark = () => {
	bookmark_add({
		id: node.id,
		icon: "folder_shared",
		label: node.name,
	})
}
</script>

<Dialog bind:this={dialog}>
	<div class="menu">
		<Button click={() => {dialog.close(); fs_download(node)}} icon="save" label="Download"/>
		{#if is_bookmark}
			<Button click={() => {dialog.close(); bookmark_del(node.id)}} icon="bookmark_remove" label="Remove bookmark"/>
		{:else}
			<Button click={() => {dialog.close(); bookmark()}} icon="bookmark_add" label="Add bookmark"/>
		{/if}
		{#if $nav.permissions.write}
			<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}
	</div>
</Dialog>

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