import { promises as fs } from "fs";

export interface Page {
	text: string;
	metadata: Metadata;
}

export interface Metadata {
	permalink: string;
	source?: string;
	sourceDir?: string;
	layout?: string;
	oldPermalink?: string;
}

export interface PostMetadata extends Metadata {
	title: string;
	htmlTitle?: string;
	slug: string;
	tags: string[];
	tagSlugs: string[];
	date: string | Date;
	readingTime?: number;
	wordCount?: number;
	excerpt?: string;
	uuid: string;
	preamble?: string;
}

export async function get(path: string): Promise<Page> {
	let text = (await fs.readFile(path)).toString();
	let metadata = {
		source: path
	} as Metadata;
	if (text.startsWith("```")) {
		const parts = text.split("```");
		text = parts.slice(2).join("```");
		const configure = new Function("metadata", parts[1]);
		configure(metadata);
	}
	return {text, metadata};
}
