import { Content } from '~/shared/content.util';
import type { ExploreContent, ContentComposable, TreeItem } from '~/types/content';

const useContentState = () => useState<ExploreContent[]>('content', () => []);

export function useContent(): ContentComposable {
    const contentState = useContentState();

    return {
        content: contentState,
        tree: computed(() => {
            const arr: TreeItem[] = [];
            for(const element of contentState.value)
            {
                addChild(arr, element);
            }
            return arr;
        }),
        fetch,
        get,
    }
}

async function fetch(force: boolean = false) {
    const content = useContentState();
    if(content.value.length === 0 || force)
        content.value = await useRequestFetch()('/api/file/overview');
}

async function get(path: string, force: boolean = false): Promise<ExploreContent | undefined> {
    const content = useContentState()
    const value = content.value;
    const item = value.find(e => e.path === path);

    if(item && !item.content)
    {
        item.content = await useRequestFetch()(`/api/file/content/${encodeURIComponent(path)}`);
    }

    content.value = value;

    return item;
}

function addChild(arr: TreeItem[], e: ExploreContent): void {
    const parent = arr.find(f => e.path.startsWith(f.path));

    if(parent)
    {
        if(!parent.children)
            parent.children = [];

        addChild(parent.children, e);
    }
    else
    {
        arr.push({ ...e });
        arr.sort((a, b) => {
            if(a.order !== b.order)
                return a.order - b.order;
            return a.title.localeCompare(b.title);
        });
    }
}