import React from "react"
import { useState } from "react"
import { useOpenDirQuery } from "../generated/graphql"
import FileBrowserElement from "./FileBrowserElement"

function parentDir(path:string): string {
	if(path.endsWith("/")){
		path = path.substr(0,path.length - 1)
	}
	const paths = path.split("/")
	paths.pop()
	return paths.join("/")
}

const FileBrowser: React.FC = () => {
	const [path,setPath] = useState("/")

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

	return (
		<div>
			<div onClick={()=>{
				setPath(parentDir(path))
			}}>
                ..
			</div>
			<div>
				{ data?.files.map(v => (<FileBrowserElement 
					key={v?.id}
					file={v}
				/>))}

				{ data?.directorys.map(v => (<FileBrowserElement
					key={v?.id}
					dir={v}
					onClick={(data)=>{
						setPath(data.id)
					}}
				/>))}
			</div>
		</div>
	)
}

export default FileBrowser
