const path = require(`path`)
const { createFilePath } = require(`gatsby-source-filesystem`)

// For all blog posts, rename yyyy-mm-dd-post-name to yyyy/mm/dd/post-name:
exports.onCreateNode = ({ node, getNode, actions }) => {
  if (node.internal.type === `MarkdownRemark`) {
    let slug = createFilePath({ node, getNode, basePath: `pages` });
    if (slug.indexOf('/blog/') > -1) {
      const dateSection = slug.match(/[0-9]{4}-[0-9]{2}-[0-9]{2}-/g)[0];
      const newDateSection = dateSection.replace(/-/g, '/');
      
      actions.createNodeField({
        node,
        name: 'slug',
        value: slug.replace(dateSection, newDateSection),
      });
    }
    else if (slug.indexOf('/notes/') > -1) {
      actions.createNodeField({
        node,
        name: 'slug',
        value: slug,
      });
    }
  }
};

// Create all blog post pages from markdown, and tags pages
exports.createPages = async ({ graphql, actions }) => {
  const result = await graphql(`
    {
      postsRemark: allMarkdownRemark(sort: {fields: [fileAbsolutePath], order: DESC}) {
        edges {
          node {
            fields {
              slug
            }
            frontmatter {
              date
              tags
            }
          }
        }
      }
      tagsGroup: allMarkdownRemark(limit: 2000) {
        group(field: frontmatter___tags) {
          fieldValue
        }
      }
    }
  `);

  if (result.errors) {
    reporter.panicOnBuild(`Error while running GraphQL query.`)
    return
  }
  
  result.data.postsRemark.edges.forEach(({ node }) => {
    const { slug } = node.fields;
      if (slug.indexOf('/blog/') > -1) {
        actions.createPage({
          path: slug,
          component: path.resolve(`./src/templates/blog-post.js`),
          context: { slug }
        });
      }
      if (slug.indexOf('/notes/') > -1) {
        actions.createPage({
          path: slug,
          component: path.resolve(`./src/templates/note.js`),
          context: { slug }
        });
      }
  });

  result.data.tagsGroup.group.forEach(tag => {
    actions.createPage({
      path: `/tags/${tag.fieldValue}/`,
      component: path.resolve(`./src/templates/tag-posts.js`),
      context: {
        tag: tag.fieldValue,
      },
    })
  })
}
