import { promises as fs } from "fs";
import * as util from "../util";
import sass, { Result as SassResult } from "sass";

function renderSass(data: string): Promise<SassResult> {
	return new Promise((resolve, reject) => {
		sass.render({
			data: data,
			outputStyle: process.env.NODE_ENV === "development" ? "expanded" : "compressed"
		}, (error, result) => {
			if (error) reject(error);
			else resolve(result);
		});
	});
}

async function generate(theme: string) {
	const filename = `site/css/${theme}.scss`;

	let sass = (await fs.readFile(filename)).toString();
	sass = util.render(sass, {}, filename);
	let css = (await renderSass(sass)).css.toString();
	css += "\n";
	let mainSass = (await fs.readFile("site/css/main.scss")).toString();
	mainSass = util.render(mainSass, {}, "site/css/main.scss");
	css += (await renderSass(mainSass)).css.toString();

	util.write(`css/${theme}.css`, css);
}

export default async function css() {
	generate("light");
	generate("dark");
	generate("auto");
}
