const fs = require('fs/promises');
const Path = require('path');
const crypto = require('crypto');
const { configuration } = require('../../../../../lib/db');
const { transform, prepare } = require('../../../../../lib/sse');
const render = require('../../../../../lib/render');
const { url2pdf } = require('../../../../../lib/selenium');

// FIXME Refactor when able
const defaultTemplatePath = require('path').resolve(__dirname, "../../../../../../../../etc/default/templates/sequence.html.njk");

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

const pdf = async function (req, res, next) {
	const fname = tmpname();
	try {
		const query = req.query;
		query.sequence = req.params.sequence;
		const {events, sequences} = await prepare(req.params.project, query);
		const seis = transform(events, sequences, {projectId: req.params.project, missingAsEvent: true});
		const template = (await configuration.get(req.params.project, "sse/templates/0/template")) || defaultTemplatePath;

		const html = await render(seis, template);

		await fs.writeFile(fname, html);
		const pdf = Buffer.from(await url2pdf("file://"+fname), "base64");

		if ("download" in query || "d" in query) {
			const extension = "pdf";
			// Get the sequence number(s) (more than one sequence can be selected)
			const seqNums = query.sequence.split(";");
			// If we've only been asked for a single sequence, get its line name
			const lineName = (sequences.find(i => i.sequence == seqNums[0]) || {})?.meta?.lineName;
			const filename = (seqNums.length  == 1 && lineName)
				? `${lineName}-NavLog.${extension}`
				: `${req.params.project}-${query.sequence}.${extension}`;
			res.set("Content-Disposition", `attachment; filename="${filename}"`);
		}
		res.status(200).send(pdf);
		next();
	} catch (err) {
		if (err.message.startsWith("template")) {
			next({message: err.message});
		} else {
			next(err);
		}
	} finally {
		await fs.unlink(fname);
	}
};

module.exports = pdf;
