---
import Layout from '../layouts/Layout.astro';
import NavBar from '../components/NavBar.astro';
import WikiEntry from '../components/WikiEntry.astro';
import WikiPageEntry from '../types/WikiPageEntry';
import { getUserByAccessToken } from '../lib/db/users';

let loggedIn = false;
const loggedToken = Astro.cookies.get('sessionToken')?.value;
const username = Astro.cookies.get('username')?.value;
if(typeof loggedToken !== 'undefined' && typeof username !== 'undefined') {
    const checkUser = await getUserByAccessToken(loggedToken);
    if(checkUser !== null && checkUser.username === username) loggedIn = true;
}

const wikiPages = await Astro.glob('../pages/wiki/**/*.md');

const pagesArray: Array<WikiPageEntry> = [{
    title: 'Home',
    url: '/wiki',
    depth: 0,
    parent: '',
    children: []
}];

const tmp = [];

for(const page of wikiPages) {
    if(typeof page.url === 'undefined') continue;
    if(page.url === '/wiki') continue;
    const url = page.url?.split('/');
    const title = page.frontmatter.title;
    const parent = url.slice(0, url.length - 1).join('/');
    const data: WikiPageEntry = {
        title,
        url: page.url,
        depth: url.length - 2,
        parent,
        children: []
    }
    tmp.push(data);
}

function findRecursively(tree: Array<WikiPageEntry>, value: string): WikiPageEntry | null {
    if(tree.length === 0) return null;
    for(const page of tree) {
        if(page.url === value) return page;
        const res = findRecursively(page.children, value)
        if(res !== null) return res;
    }

    return null;
}

for(const page of tmp.sort((a, b) => a.depth - b.depth)) {
    if(page.depth === 1) {
        pagesArray.push(page);
    } else {
        const parent = findRecursively(pagesArray, page.parent);
        if(parent !== null) parent.children.push(page);
    }
}

const { frontmatter } = Astro.props;
---
<Layout title="Wiki">
	<NavBar loggedIn=`${loggedIn}` active="wiki" />
    <div class="container">
        <div class="sidebar">
            <ul>
                {pagesArray.map(page => <WikiEntry entry={page} />)}
            </ul>
        </div>
        <div class="content">
            <h1>{frontmatter.title}</h1>
            <div class="markdown">
				<slot />
			</div>
        </div>
    </div>
</Layout>
<style>
* {
    color: white;
}

.container {
    display: flex;
    flex-direction: row;
    margin-top: 15px;
}

.sidebar {
    width: 30rem;
    height: 100%;
    border-right: 3px solid rgb(77, 76, 78);
}

.content {
    width: calc(100% - 30rem);
    margin-left: 8em;
    margin-right: 22em;
    overflow-wrap: break-word;
}
</style>