import type { SvelteComponent } from 'svelte';
import type { MDsveXComponent } from '$lib/types';

export interface BlogEntry {
    title: string;
    src: string;
    src_target: string;
    img: string;
    scale: string;
    date: string;
    desc: string;
}


export function load() {
    const blog_entries: BlogEntry[] =
        Object.entries(import.meta.glob('/src/routes/blogs/**/+page.svx', { eager: true }))
            .map(([key, value]) => {
                return {
                    src: key.split('/src/routes').pop()?.split('/+page.svx').slice(0, -1).pop() as string,
                    metadata: (value as MDsveXComponent).metadata
                } as Record<string, any>
            })
            .filter(entry => entry.metadata.listed)
            .map(entry => {
                entry.src = (entry.metadata.src ?? entry.src) as string;
                entry.title = entry.metadata.title as string ?? "Needs Title!!";
                entry.desc = entry.metadata.desc as string ?? "Needs Description!!";
                entry.date = Date.parse(entry.metadata.date as string ?? "");
                entry.src_target = (entry.src.includes('https://') || entry.src.includes('http://')) ? '_blank' : '';
                [entry.img, entry.scale = ""] = (entry.metadata?.img_cov as string ?? "blog-1.png").split('|');
                entry.img_bg = entry.metadata.img_bg == "dark" ? "var(--rp-moon-base" : "var(--rp-moon-text)";
                entry.scale = (entry.scale == "") ? "" : "transform: scale(" + entry.scale + "); height:auto;border-radius:0;";

                return entry;
            })
            .sort((a, b) => b.date - a.date)
            .map((entry) => {
                entry.date = new Date(entry.date).toDateString();
                return entry as BlogEntry;
            })
    return {
        blogs: blog_entries
    };
}
