import path from "path";
import * as util from "../util";
import * as metadata from "../metadata";
import { Page, PostMetadata } from "../metadata";
import layout from "../layout";

export default async function generatePaginated(posts: Page[], basePath: string, templatePath: string, extraData?: object, extraMetadata?: object) {
	const page = await metadata.get(templatePath);

	if (extraMetadata) page.metadata = {...page.metadata, ...extraMetadata};

	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 chunks = util.chunk(posts, 5);
	for (const {chunk, index} of chunks) {
		const pageNum = index + 1;

		let data = {
			metadata: page.metadata,
			posts: chunk,
			pagination: {
				current: pageNum,
				total: chunks.length,
				prevLink: pageNum == 1 ? "" : pageNum == 2 ? basePath : path.join(basePath, (pageNum - 1).toString()),
				nextLink: pageNum == chunks.length ? "" : path.join(basePath, (pageNum + 1).toString())
			}
		};
		if (extraData) data = {...data, ...extraData};

		let renderedTemplate = util.render(page.text, data, templatePath);

		renderedTemplate = await layout(renderedTemplate, page.metadata, page.metadata.layout!);

		util.write(path.join(basePath, pageNum.toString(), "index.html"), renderedTemplate);

		if (pageNum == 1) {
			util.write(path.join(basePath, "index.html"), renderedTemplate);
		}
	}
}