const { AsyncParser } = require('json2csv');
const { plan } = require('../../../../lib/db');

const json = async function (req, res, next) {
	try {
		const response = await plan.list(req.params.project, req.query);

		if ("download" in req.query || "d" in req.query) {
			const extension = "html";
			const filename = `${req.params.project.toUpperCase()}-Plan.${extension}`;
			res.set("Content-Disposition", `attachment; filename="${filename}"`);
		}

		const transforms = (i) => {
			i.lon0 = Number(((i?.geometry?.coordinates||[])[0]||[])[0]).toFixed(6)*1;
			i.lat0 = Number(((i?.geometry?.coordinates||[])[0]||[])[1]).toFixed(6)*1;
			i.lon1 = Number(((i?.geometry?.coordinates||[])[1]||[])[0]).toFixed(6)*1;
			i.lat1 = Number(((i?.geometry?.coordinates||[])[1]||[])[1]).toFixed(6)*1;
			i.duration = i.duration?.hours*3600 + i.duration?.minutes*60 + i.duration?.seconds;
			delete i.class;
			delete i.geometry;
			delete i.meta;
			return i;
		};

		const csv = new AsyncParser({transforms}, {objectMode: true});
		csv.processor.on('error', (err) => { throw err; });
		csv.processor.on('end', () => {
			res.end();
			next();
		});

		res.status(200);
		csv.processor.pipe(res);
		response.forEach(row => csv.input.push(row));
		csv.input.push(null);
	} catch (err) {
		next(err);
	}
};

module.exports = json;
