<script setup lang="ts">
import { PermissionAreas } from '#shared/helpers.ts';
import { adminStorageRefreshInjectionKey } from '#shared/injectionKeys.ts';
import AdminStorageTree from '~/components/admin/AdminStorageTree.vue';

const sizesAsyncData = useFetch('/api/admin/storage/sizes', { lazy: true });

provide(adminStorageRefreshInjectionKey, sizesAsyncData.refresh);

const tree = computed(() => {
    const tree = new Map();
    for (const [key, size] of Object.entries(sizesAsyncData.data.value ?? {})) {
        const path = key.split(':');
        let subtree = tree;
        for (const chunk of path.slice(0, path.length - 1)) {
            if (!subtree.has(chunk)) {
                subtree.set(chunk, new Map());
            }
            subtree = subtree.get(chunk);
        }
        subtree.set(path[path.length - 1], size);
    }
    return tree;
});
</script>

<template>
    <Page>
        <NotFound v-if="!$isGranted(PermissionAreas.Code)" />
        <template v-else>
            <p>
                <nuxt-link to="/admin">
                    <Icon v="user-cog" />
                    <T>admin.header</T>
                </nuxt-link>
            </p>
            <h2>
                <Icon v="layer-group" />
                Storage
            </h2>

            <p>
                Gives an overview about mounted storages.
            </p>

            <button type="button" class="btn btn-outline-secondary" @click="sizesAsyncData.execute()">
                <Icon v="sync" />
                Refresh
            </button>

            <Loading :value="sizesAsyncData.data.value">
                <template v-for="[chunk, node] of tree.entries()" :key="chunk">
                    <AdminStorageTree v-if="node instanceof Map" :item-key="chunk" :tree="node" />
                    <AdminStorageItem v-else :item-key="chunk" :size="node" />
                </template>
            </Loading>
        </template>
    </Page>
</template>
