<script lang="ts">
import Button from "layout/Button.svelte";
import { fs_trash, type FSNode } from "lib/FilesystemAPI.svelte";
import type { FSNavigator } from "filesystem/FSNavigator";
import { loading_finish, loading_start } from "lib/Loading";

let {
	nav,
	file = $bindable({} as FSNode),
	new_name = $bindable(),
	visible = $bindable(),
	open_after_edit = $bindable(false)
}: {
	nav: FSNavigator;
	file?: FSNode;
	new_name: string;
	visible: boolean;
	open_after_edit: boolean;
} = $props();

let is_root_dir = $derived(file.path === "/"+file.id)

const delete_file = async (e: MouseEvent) => {
	e.preventDefault()

	try {
		loading_start()
		await fs_trash(file.path)
	} catch (err) {
		console.error(err)
		alert(err)
		return
	} finally {
		loading_finish()
	}

	if (open_after_edit) {
		nav.navigate(file.path, false)
	} else {
		nav.reload()
	}
	visible = false
}
</script>

<fieldset>
	<legend>File settings</legend>
	{#if is_root_dir}
		<div class="highlight_yellow">
			Filesystem root cannot be renamed. If this shared directory is in <a
			href="/d/me">your filesystem</a> you can rename it from there
		</div>
	{/if}
	<div class="form_grid">
		<label for="file_name">Name</label>
		<input form="edit_form" bind:value={new_name} id="file_name" type="text" class="form_input" disabled={is_root_dir}/>
	</div>
</fieldset>

{#if $nav.permissions.delete === true}
	<fieldset>
		<legend>Delete</legend>
		<p>
			Move this file or directory to the trash. You can restore it or
			permanently delete it from the <a href="/d/me/.Trash">trash bin</a>.
		</p>
		<Button click={delete_file} red icon="delete" label="Move to trash" style="align-self: flex-start;"/>
	</fieldset>
{/if}

<style>
.form_grid {
	display: grid;
	grid-template-columns: 1fr 10fr;
	align-items: center;
}
</style>
