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

export default function Tag({ data, pageContext }) {
    var { tag } = 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={'Tag: ' + tag + ' (' + totalCount + ')'}>
            <p>
                All posts tagged with "{tag}".
            </p>
            <ul>
                {postListItems}
            </ul>
		</Page>
	)
}

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