import Head from "next/head";
import Layout from "../../components/Layout";
import Util from "../../lib/utils"
import FolderTree from "../../components/FolderTree";
import MDContent from "../../components/MDContent";


export default function Home({ note, backLinks, fileNames, tree, flattenNodes }) {

  return (
    <Layout>
      <Head>
        {note.title && <meta name="title" content={note.title} />}
      </Head>
      <div className='notes-container'>
        <nav className="nav-bar">
          <FolderTree tree={tree} flattenNodes={flattenNodes} />
        </nav>
        <MDContent content={note.data} handleOpenNewContent={null} backLinks={backLinks} />
      </div>
    </Layout>
  );
}

export async function getStaticPaths() {
  const allPostsData = Util.getAllSlugs();
  const paths = allPostsData.map(p => ({ params: { id: p } }))

  return {
    paths,
    fallback: false
  };
}


export function getStaticProps({ params }) {
  const { nodes, edges } = Util.constructGraphData()
  const note = Util.getSinglePost(params.id);
  const tree = Util.convertObject(Util.getDirectoryData());
  const flattenNodes = Util.getFlattenArray(tree)

  const listOfEdges: unknown[] = edges.filter(anEdge => anEdge.target === params.id)
  const internalLinks: unknown[] = listOfEdges.map((anEdge: { source: string }) => nodes.find(aNode => aNode.slug === anEdge.source)).filter(element => element !== undefined)
  const backLinks = [...new Set(internalLinks)]
  return {
    props: {
      note,
      tree: tree,
      flattenNodes: flattenNodes,
      backLinks: backLinks.filter((link: { slug: string }) => link.slug !== params.id),
    },
  };
}
