import React from "react"
import { useState } from "react"
import uploadFile from "../functions/uploadFile"
import { useOpenDirQuery } from "../generated/graphql"
import Breadcrum from "./Breadcrum"
import DragAndDrop from "./DragAndDrop"
import FileBrowserElement from "./FileBrowserElement"
import FileOpen from "./FileOpen"

const FileBrowser: React.FC = () => {
	const [path,setPath] = useState("/")
	const [openFileId, setOpenFileId] = useState("")
	const [showFile, setShowFile] = useState(false)

	const { data, loading } = useOpenDirQuery({
		variables:{
			path
		}
	})

	async function handleDrop(files:FileList) {
		const wait: Promise<boolean>[] = []
		for (let i = 0; i < files.length; i++) {
			const file = files[i]
			wait.push(uploadFile(file, path + file.name))
		}

		await Promise.all(wait)
	}

	return (
		<div>
			<DragAndDrop
				handleDrop={async (files)=>{
					await handleDrop(files)
				}}
			>
				<Breadcrum path={path} onDirClick={(newPath)=>{
					setPath(newPath)
				}}/>
				<div>
					{loading && 
						<div className="loading loading-lg"></div> // TODO: center
					}
					<table className="table table-striped table-hover">
						<thead>
							<tr>
								<th>Name</th>
								<th>Last Modified</th>
								<th>Size</th>
							</tr>
						</thead>
						<tbody>

							{ data?.directorys.map(v => (<FileBrowserElement
								key={v?.id}
								dir={v}
								onClick={(dir)=>{
									setPath(dir.id)
								}}
							/>))}
								
							{ data?.files.map(v => (<FileBrowserElement 
								key={v?.id}
								file={v}
								onClick={(file)=>{
									setOpenFileId(file.id)
									setShowFile(true)
								}}
							/>))}
						</tbody>
					</table>
				</div>
				{<FileOpen id={openFileId} show={showFile} onCloseClick={()=>{
					setShowFile(false)
				}} />}
			</DragAndDrop>
		</div>
	)
}

export default FileBrowser
