import { Page, PostMetadata } from "../metadata";
import generatePaginated from "./paginated";
import slugify from "@sindresorhus/slugify";

export default async function(posts: Page[]): Promise<Map<string, Page[]>> {
	const taggedPosts = new Map<string, Page[]>();

	for (const post of posts) {
		const tags = (<PostMetadata>post.metadata).tags;
		for (const tag of tags) {
			if (!taggedPosts.has(tag)) {
				taggedPosts.set(tag, []);
			}
			taggedPosts.get(tag)!.push(post);
		}
	}

	taggedPosts.forEach((tagPosts, tag) => {
		generatePaginated(tagPosts, `/${slugify(tag)}/`, "site/tag.html.ejs", {
			tag
		}, {
			title: `${tag} posts`
		});
	});

	return taggedPosts;
}
