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

const json = async function (req, res, next) {
	try {
		const query = req.query;
		query.sequence = req.params.sequence;
		const {events, sequences} = await prepare(req.params.project, query);
		if ("download" in query || "d" in query) {
			const extension = "json";
			// 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(events);
		next();
	} catch (err) {
		next(err);
	}
};

module.exports = json;
