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

import React from "react";
import Navbar from "../components/navbar";
import { graphql } from "gatsby";
import style from "./notes.module.css";

export default ({ data, pageContext }) => {
  const posts = data.allMdx.edges;
  const { currentPage, numPages, rootPath } = pageContext;
  let prevPageLink = null;

  if (currentPage === 2) {
    prevPageLink = <a href={rootPath} className={style.prevPageLink}>&lt;&lt;</a>;
  } else if (currentPage !== 1) {
    prevPageLink = <a href={rootPath + '/' + (currentPage - 1)} className={style.prevPageLink}>&lt;&lt;</a>;
  }

  const shouldDisplayNav = numPages !== 1;

  return (
    <>
      <Navbar />
      {posts.map(({ node }) => {
        const frontmatter = node.frontmatter
        return (
          <article key={frontmatter.title}>
            <div className={style.noteTitle}>
              <h3>
                <a href={`${rootPath + '/' + frontmatter.path}`}>{frontmatter.title}</a>
              </h3>
              <time dateTime={frontmatter.date}>{frontmatter.date}</time>
            </div>
            <p>{node.excerpt}</p>
          </article>
        )
      })}
      {shouldDisplayNav &&
        <p className={style.paginationNav}>
          {prevPageLink}
          {currentPage}
          {currentPage !== numPages &&
            <a
              href={rootPath + '/' + (currentPage + 1)}
              className={style.nextPageLink}>
              &gt;&gt;
            </a>
          }
        </p>
      }
    </>
  )
}

export const query = graphql`
  query IndexQuery($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
        }
      }
    }
  }
`
