<script lang="ts">
import { formatDataVolume, formatDate, formatThousands } from "util/Formatting";
import { fs_encode_path, fs_node_icon } from "lib/FilesystemAPI.svelte"
import type { FSNavigator } from "filesystem/FSNavigator";
import SortButton from "layout/SortButton.svelte";
import { FileAction, type FileActionHandler } from "./FileManagerLib";
import Dialog from "layout/Dialog.svelte";
import Button from "layout/Button.svelte";
import { onMount } from "svelte";
import CopyButton from "layout/CopyButton.svelte";

let {
	nav,
	file_event,
	show_hidden = false,
	large_icons = false,
	hide_edit = false,
	hide_branding = false
}: {
	nav: FSNavigator
	file_event: FileActionHandler
	show_hidden?: boolean
	large_icons?: boolean
	hide_edit?: boolean
	hide_branding?: boolean
} = $props();

let dialog: Dialog = $state()
const columns: {field: string, label: string}[] = [
	{field: "modified", label: "Modified on"},
	{field: "created", label: "Created on"},
	{field: "created_by", label: "Created by"},
	{field: "mode", label: "Mode"},
	{field: "recursive_children", label: "Children"},
	{field: "file_type", label: "File type"},
	{field: "size", label: "Size"},
	{field: "id", label: "Node ID"},
]
let config: {
	modified?: boolean
	created?: boolean
	created_by?: boolean
	mode?: boolean
	recursive_children?: boolean
	file_type?: boolean
	size?: boolean
	id?: boolean
} = $state({
	size: true, // Only size is visible by default
})

const prevent = (e: MouseEvent) => {
	e.stopPropagation()
}

const submit_settings = (e: SubmitEvent) => {
	e.preventDefault()
	dialog.close()
}
const save_settings = () => {
	window.localStorage.setItem("list_view_columns", JSON.stringify(config))
}
const load_settings = () => {
	let item = window.localStorage.getItem("list_view_columns")
	if (item !== null) {
		config = JSON.parse(item)
	}
}
onMount(load_settings)
</script>

<table class="directory">
	<thead>
		<tr class="header_row">
			<td></td>
			<td>
				<SortButton active_field={$nav.sort_last_field} asc={$nav.sort_asc} sort_func={nav.sort_children} field="name">
					Name
				</SortButton>
			</td>
			{#each columns as col}
				<td class="hide_small" class:hidden={!config[col.field]}>
					<SortButton active_field={$nav.sort_last_field} asc={$nav.sort_asc} sort_func={nav.sort_children} field={col.field}>
						{col.label}
					</SortButton>
				</td>
			{/each}
			<td class="node_icons icons_wrap">
				<Button flat icon="settings" click={e => dialog.open(e)} />
			</td>
		</tr>
	</thead>
	<tbody>
		{#each $nav.children as child, index (child.path)}
			<tr
				onclick={e => file_event(FileAction.Click, index, e)}
				oncontextmenu={e => file_event(FileAction.Context, index, e)}
				class="node"
				class:node_selected={child.fm_selected}
				class:hidden={child.name.startsWith(".") && !show_hidden}
			>
				<td>
					<img src={fs_node_icon(child, 64, 64)} class="node_icon" class:large_icons alt="icon"/>
				</td>
				<td class="node_name">
					<a class="title_link" href={"/d"+fs_encode_path(child.path)}>
						{child.name}
					</a>
				</td>
				<td class="node_size hide_small" class:hidden={!config.modified}>
					{formatDate(child.modified, true, true, false)}
				</td>
				<td class="node_size hide_small" class:hidden={!config.created}>
					{formatDate(child.created, true, true, false)}
				</td>
				<td class="node_size hide_small" class:hidden={!config.created_by}>
					{child.created_by}
				</td>
				<td class="node_size hide_small" class:hidden={!config.mode}>
					{child.mode_string}
				</td>
				<td class="node_size hide_small" class:hidden={!config.recursive_children}>
					{formatThousands(child.recursive_children)}
				</td>
				<td class="node_size hide_small" class:hidden={!config.file_type}>
					{child.file_type}
				</td>
				<td class="node_size hide_small" class:hidden={!config.size}>
					{#if child.type === "file"}
						{formatDataVolume(child.file_size, 3)}
					{:else if child.type === "dir"}
						{formatDataVolume(child.recursive_size, 3)}
					{/if}
				</td>
				<td class="node_size hide_small" class:hidden={!config.id}>
					<CopyButton text={$nav.base.id} onclick={prevent} />
					<a href="/d/{child.id}" onclick={prevent}>{child.id}</a>
				</td>
				<td class="node_icons">
					<div class="icons_wrap">
						{#if child.abuse_type !== undefined}
							<i class="icon" title="This file / directory has received an abuse report. It cannot be shared">block</i>
						{:else if child.is_shared()}
							<a
								href="/d/{child.id}"
								onclick={e => file_event(FileAction.Share, index, e)}
								class="button action_button"
							>
								<i class="icon" title="This file / directory is shared. Click to open public link">share</i>
							</a>
						{/if}
						{#if child.properties !== undefined && child.properties.branding_enabled === "true" && !hide_branding}
							<button class="action_button" onclick={e => file_event(FileAction.Branding, index, e)}>
								<i class="icon">palette</i>
							</button>
						{/if}
						{#if !hide_edit}
							<button class="action_button" onclick={e => file_event(FileAction.Menu, index, e)}>
								<i class="icon">menu</i>
							</button>
						{/if}
					</div>
				</td>
			</tr>
		{/each}
	</tbody>
</table>


<Dialog bind:this={dialog} onclose={save_settings}>
	<form class="column_config" onsubmit={submit_settings}>
		{#each columns as col}
			<div>
				<input type="checkbox" id="show_{col.field}" name="show_{col.field}" bind:checked={config[col.field]}/>
				<label for="show_{col.field}">{col.label}</label>
			</div>
		{/each}
		<button type="submit">
			<i class="icon">save</i>
			Save
		</button>
	</form>
</Dialog>

<style>
.directory {
	background: var(--body_background);
	border-collapse: collapse;
	backdrop-filter: blur(4px);
	max-width: 1200px;
	margin: auto; /* center */
}
td {
	padding-top: 0;
	padding-bottom: 0;
	padding-left: 0;
}
.header_row {
	white-space: nowrap;
}
.node_icons {
	padding: 0;
}
.node {
	text-decoration: none;
	color: var(--body_text-color);
	cursor: pointer;
}
.node:not(:last-child) {
	border-bottom: 1px solid var(--separator);
}
.node:hover:not(.node_selected) {
	background: var(--input_hover_background);
	color: var(--input_text);
	text-decoration: none;
}
.node.node_selected {
	background-color: var(--highlight_color) !important;
	color: var(--highlight_text_color);
}
td {
	vertical-align: middle;
}
.node_icon {
	height: 32px;
	width: 32px;
	vertical-align: middle;
	/* border-radius: 4px; */
	margin: 2px;
}
.node_name {
	width: 100%;
	line-height: 1.2em;
	word-break: break-all;
}
.title_link {
	text-decoration: none;
	color: var(--body_text_color);
}
.node_size {
	min-width: 5em;
	white-space: nowrap;
}
.icons_wrap {
	display: flex;
	flex-direction: row;
	justify-content: end;
}
.hidden {
	display: none;
}

.column_config {
	display: flex;
	flex-direction: column;
	white-space: nowrap;
}

/* Large icon mode only supported on wide screens */
@media (min-width: 500px) {
	.node_icon.large_icons {
		height: 64px;
		width: 64px;
	}
}
@media (max-width: 500px) {
	.hide_small {
		display: none;
	}
}
</style>
