const fs = require('fs/promises');
const Path = require('path');
const crypto = require('crypto');
const { url2pdf } = require('../../selenium');
const html = require('./html');
const filename = require('./filename');


function tmpname (tmpdir="/dev/shm") {
	return Path.join(tmpdir, crypto.randomBytes(16).toString('hex')+".tmp");
}

async function makePDF (text) {
	const fname = tmpname();
	try {
		await fs.writeFile(fname, text);
		const pdf = Buffer.from(await url2pdf("file://"+fname), "base64");
		return pdf;
	} catch (err) {
		if (err.message.startsWith("template")) {
			throw {message: err.message};
		} else {
			throw err;
		}
	} finally {
		await fs.unlink(fname);
	}
}

async function pdf ({project, sequence}, seisdata) {

	const htmlData = await html({project, sequence}, seisdata);
	const text = htmlData.data;
	const data = await makePDF(text);
	const name = filename(seisdata?.name, ".pdf");

	return { name, data, mimetype: "application/pdf" };
}

module.exports = pdf;
