// const { configuration } = require('../../../../lib/db');
const { plan, gis, info } = require('../../../../lib/db');
const leafletMap = require('../../../../lib/map');
const render = require('../../../../lib/render');

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

const html = async function (req, res, next) {
	try {
		const planInfo = await info.get(req.params.project, "plan", req.query);
		const lines = await plan.list(req.params.project, req.query);
		const preplotGeoJSON = await gis.project.preplot.lines(req.params.project, {class: "V", ...req.query});
		const linesGeoJSON = lines.filter(plan => plan.geometry).map(plan => {
			const feature = {
				type: "Feature",
				geometry: plan.geometry,
				properties: plan
			};
			delete feature.properties.geometry;
			return feature;
		});

// 		const template = (await configuration.get(req.params.project, "sse/templates/0/template")) || defaultTemplatePath;
		const template = defaultTemplatePath;

		const mapConfig = {
			size: { width: 500, height: 500 },
			layers: [
				{
					features: preplotGeoJSON,
					options: {
						style (feature) {
							return {
								opacity: feature.properties.ntba ? 0.2 : 0.5,
								color: "gray",
								weight: 1
							}
						}
					}
				},
				{
					features: linesGeoJSON,
					options: {
						style (feature) {
							return {
								color: "magenta",
								weight: 2
							}
						}
					}
				}
			]
		}

		const map = leafletMap(mapConfig);

		const data = {
			projectId: req.params.project,
			info: planInfo,
			lines,
			map: await map.getImageData()
		}

		const response = await render(data, template);

		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}"`);
		}
		res.status(200).send(response);
		next();
	} catch (err) {
		if (err.message.startsWith("template")) {
			next({message: err.message});
		} else {
			next(err);
		}
	}
};

module.exports = html;
