<script>
    import {getContext} from "svelte";
    import Folder from "./Folder.svelte";

    export let schema;
    const channel = getContext("channel");
    const readableSchemas = getContext("readableSchemas");

    function addToFolder(tree, folderPath, aSchema) {
        let shouldExpand = aSchema.name === schema?.name;
        if (folderPath === "") {
            tree.files.push(aSchema)
            return tree
        }
        const folderNames = folderPath.split(".");
        folderNames.forEach(folderName => {
            let queriedFolder = tree.folders.find(folder => folder.name === folderName)
            if (!queriedFolder) {
                queriedFolder = {name: folderName, files: [], folders: [], shouldExpand: shouldExpand};
            }
            folderNames.shift()
            let remainingFolderPath = folderNames.join(".");
            queriedFolder =  addToFolder(queriedFolder, remainingFolderPath, aSchema)

            tree.folders = tree.folders.filter(f => f.name !== queriedFolder.name)
            tree.folders.push(queriedFolder);

        })

        return tree;
    }

    const schemaTree = readableSchemas.reduce((carry, schema) => {
        carry = addToFolder(carry, schema.folder,schema)
        return carry;
    }, {name: "", files: [], folders: [], shouldExpand:true});
</script>
<div class="sidebar-top">
    <a class="logo" href="{channel.lucentUrl}">{channel.name}</a>
    <a class="nav-item" href="{channel.lucentUrl}/profile">
    </a>
</div>
<div class="sidebar">
    <Folder folder={schemaTree} {schema}  ></Folder>
</div>
