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

exports.onCreateNode = ({ node, getNode, actions }) => {
    const { createNodeField } = actions;

    if (node.internal.type === `MarkdownRemark`) {
        var slug = createFilePath({ node, getNode, basePath: `pages` });
        var date = new Date(node.frontmatter.date);
        var year = date.getFullYear();
        var month = date.getMonth();
        createNodeField({
            node,
            name: `slug`,
            value: slug,
        });
        createNodeField({
            node,
            name: `year`,
            value: year,
        });
        createNodeField({
            node,
            name: `month`,
            value: month,
        });
    }
};

exports.createPages = async ({ graphql, actions }) => {
    const { createPage } = actions;

    const result = await graphql(`
        query {
            postsRemark: allMarkdownRemark {
                edges {
                    node {
                        fields {
                            slug
                        }
                    }
                }
            }
            tagsGroup: allMarkdownRemark {
                group(field: frontmatter___tags) {
                    fieldValue
                }
            }
            categoriesGroup: allMarkdownRemark {
                group(field: frontmatter___categories) {
                    fieldValue
                }
            }
        }
    `);

    result.data.postsRemark.edges.forEach(({ node }) => {
        createPage({
            path: node.fields.slug,
            component: path.resolve(`./src/templates/post.js`),
            context: {
                slug: node.fields.slug
            }
        });
    });

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

    result.data.categoriesGroup.group.forEach((category) => {
        createPage({
            path: `/categories/${category.fieldValue}/`,
            component: path.resolve(`./src/templates/category.js`),
            context: {
                category: category.fieldValue
            }
        });
    });
};