/*
 * This file handles rendering the pages that let users select and find notes.
 * See note.tsx for rendering a single note.
 */

import Navbar from '../components/navbar';
import PaginationNav from '../components/pagination';
import React from 'react';
import { graphql } from 'gatsby';
import { noteTitle } from './notes.module.css';

export default ({ data, pageContext }): JSX.Element => {
  const posts = data.allMdx.edges;
  const { currentPage, numPages, rootPath } = pageContext;

  return (
    <>
      <Navbar />
      {posts.map(({ node }) => {
        const frontmatter = node.frontmatter;
        return (
          <article key={frontmatter.title}>
            <div className={noteTitle}>
              <h3>
                <a href={`${rootPath + '/' + frontmatter.path}`}>
                  {frontmatter.title}
                </a>
              </h3>
              <time dateTime={frontmatter.date}>{frontmatter.date}</time>
            </div>
            <p>{node.excerpt}</p>
          </article>
        );
      })}
      <PaginationNav
        currentPage={currentPage}
        numPages={numPages}
        rootPath={rootPath}
      />
    </>
  );
};

export const query = graphql`
  query NotesIndexQuery($skip: Int!, $limit: Int!) {
    allMdx(
      sort: { order: DESC, fields: [frontmatter___date] }
      filter: {
        fileAbsolutePath: { glob: "**/src/notes/*" }
        frontmatter: { hidden: { ne: true } }
      }
      limit: $limit
      skip: $skip
    ) {
      edges {
        node {
          excerpt(pruneLength: 250)
          frontmatter {
            title
            date(formatString: "YYYY-MM-DD")
            path
          }
          id
        }
      }
    }
  }
`;
