import React from "react"
import { useState } from "react"
import { useOpenDirQuery } from "../generated/graphql"
import Breadcrum from "./Breadcrum"
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
		}
	})

	return (
		<div>
			<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>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)
			}} />}
		</div>
	)
}

export default FileBrowser
