const { configuration } = require('../../../../../lib/db');
const { transform, prepare } = require('../../../../../lib/sse');
const render = require('../../../../../lib/render');

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

const html = async function (req, res, next) {
	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;
// 		console.log("TEMPLATE", template);

		const response = await render(seis, template);

		if ("download" in query || "d" in query) {
			const extension = "html";
			// 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(response);
		next();
	} catch (err) {
		if (err.message.startsWith("template")) {
			next({message: err.message});
		} else {
			next(err);
		}
	}
};

module.exports = html;
