import RenderWithoutJS from "@/components/RenderWithoutJS";
import Sidebar from "@/components/Sidebar";
import index from "@/styles/Index.module.sass"
import Lanyard from "@/components/Lanyard"
import { remark } from "remark"
import remarkFrontmatter from "remark-frontmatter"
import { read } from "to-vfile"
import listFiles from "@/lib/listFiles";
import Markdown from 'markdown-to-jsx';
import Link from "@/components/Link";
import Image from "@/components/Image";
import Head from "next/head";
import matter from "gray-matter";
const Post = (props: { post: string, slug: string, matter: any }) => {

    // console.log(props.matter)

    return (
        <RenderWithoutJS>
            <main id={index.layout}>
                <Head>
                    <title>{props.matter.title} | lio's blog</title>
                </Head>
                <Sidebar />
                <section id={index.main}>
                    <Markdown
                        children={props.post}
                        options={{
                            overrides: {
                                a: ({ ...props }) => <Link href={props.href} title={props.children} withArrow />,
                                img: ({ ...props }) => <Image src={props.src} alt={props.alt} />,
                                p: ({ children, ...props }) => {
                                    const ParaComponent = children[0]?.type?.name === 'img' ? 'div' : 'p'
                                    return <ParaComponent {...props}>{children}</ParaComponent>
                                },
                            }
                        }}
                    />
                </section>
                <Lanyard />
            </main>
        </RenderWithoutJS>
    );

};

export default Post

export async function getStaticProps(context: any) {
    let post = await remark()
        .use(remarkFrontmatter)
        .process(await read(`${listFiles('./src/blog').find(file => file.includes(context.params.slug))}`))
    return {
        props: {
            post: (post.value as string).replace(/^(---)\n*([a-zA-Z0-9\/\#[\]\"_:,\-\s*]*)(---)$/mi, ""),
            matter: matter(post.value).data,
            slug: context.params.slug
        }
    }
}


export async function getStaticPaths() {
    let path = './src/blog'
    let paths = listFiles(path).map(file => file.replace(path, "/blog").replace(/.mdx?/gmi, ''))
    // console.log(paths)
    return {
        paths,
        fallback: true
    }
}