import React from "react";
import { graphql } from "gatsby";
import Page from "./page";

export default function Category({ data, pageContext }) {
    var { category } = pageContext;
    var siteMetadata = data.site.siteMetadata;
    var totalCount = data.allMarkdownRemark.totalCount;
    var postListItems = data.allMarkdownRemark.edges.map(function(edge) {
        return (
            <li><a href={edge.node.fields.slug}>{edge.node.frontmatter.title}</a></li>
        );
    });

	return (
		<Page headerInfo={siteMetadata} pageTitle={'Category: ' + category + ' (' + totalCount + ')'}>
            <p>
                All posts categorized under "{category}".
            </p>
            <ul>
                {postListItems}
            </ul>
		</Page>
	)
}

export const query = graphql`
    query($category: String!) {
        allMarkdownRemark(
            sort: { fields: [frontmatter___date], order: DESC }
            filter: { frontmatter: { categories: { in: [$category] } } }
        )
        {
            totalCount
            edges {
                node {
                    fields {
                        slug
                    }
                    frontmatter {
                        title
                    }
                }
            }
        }
        site {
            ...HeaderInfo
        }
    }
`