import path from "path";
import * as metadata from "./metadata";
import { Metadata } from "./metadata";
import * as util from "./util";

// create the date once so that every page uses the same value
const stylesheetCacheBuster = new Date().getTime();

export default async function layout(text: string, pageMetadata: Metadata, layoutPath: string): Promise<string> {
	const layoutFile = path.join("site/layouts", layoutPath);
	let layoutPage = await metadata.get(layoutFile);
	text = util.render(layoutPage.text, {
		content: text,
		metadata: pageMetadata,
		stylesheetCacheBuster,
	}, layoutFile);
	if (layoutPage.metadata.layout) {
		return await layout(text, pageMetadata, layoutPage.metadata.layout);
	} else {
		return text;
	}
}
