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

let { nav }: { nav: FSNavigator } = $props();

let name_input: HTMLInputElement = $state();
let new_dir_name = $state("")
let error_msg = $state("")
let create_dir = async (e: SubmitEvent) => {
	e.preventDefault()

	let form = new FormData()
	form.append("type", "dir")

	try {
		loading_start()
		await fs_mkdir(nav.base.path+"/"+new_dir_name)
		new_dir_name = "" // Clear input field
		error_msg = "" // Clear error msg
		nav.reload()
	} catch (err) {
		if (err.value && err.value === "node_already_exists") {
			error_msg = "A directory with this name already exists"
		} else {
			error_msg = "Server returned an error: code: '"+err.value+"' message: "+err.message
		}
	} finally {
		loading_finish()
	}
}

onMount(() => {
	name_input.focus()
})
</script>

{#if error_msg !== ""}
	<div class="highlight_yellow create_dir">
		{error_msg}
	</div>
{/if}

<form id="create_dir_form" class="create_dir" onsubmit={create_dir}>
	<img src="/res/img/mime/folder.png" class="icon" alt="icon"/>
	<input class="dirname" type="text" bind:this={name_input} bind:value={new_dir_name} />
	<Button form="create_dir_form" type="submit" icon="create_new_folder" label="Create"/>
</form>

<style>
.create_dir {
	display: flex;
	flex-direction: row;
	width: 100%;
	max-width: 1000px;
	margin: auto;
}
.icon {
	align-self: center;
	height: 32px;
	width: 32px;
	flex: 0 0 auto;
}
.dirname {
	flex: 1 1 auto;
}
</style>
