import { promises as fs } from "fs";
import path from "path";
import { Page, PostMetadata } from "../metadata";
import * as util from "../util";
import { TutorialSeries } from "./tutorials";

async function generateFeed(posts: Page[], permalink: string, tag?: string) {
	posts = posts.sort((a, b) => {
		const aDate = <Date>(<PostMetadata>a.metadata).date;
		const bDate = <Date>(<PostMetadata>b.metadata).date;
		return bDate.getTime() - aDate.getTime();
	});

	const dest = path.join(permalink, "feed.xml");

	let text = (await fs.readFile("site/feed.xml.ejs")).toString();
	text = util.render(text, {
		posts,
		tag,
		permalink,
		feedPath: dest
	}, "site/feed.xml.ejs");

	util.write(dest, text);
}

export async function posts(posts: Page[]) {
	generateFeed(posts, "/");
}

export async function tags(tags: Map<string, Page[]>) {
	tags.forEach((posts, tag) => {
		generateFeed(posts, `/${tag}/`, tag);
	});
}

export async function tutorials(tutorials: TutorialSeries[]) {
	tutorials.forEach(series => {
		generateFeed(series.posts, `/tutorials/${series.series}/`, series.seriesName);
	});
}
