
const { gis } = require('../../../../lib/db');

function makeOptions (query) {
	const options = {};

	if (query.hasOwnProperty("limit")) {
		options.limit = Math.abs(Number(query.limit));
	}

	if (query.hasOwnProperty("bbox")) {
		options.bbox = query.bbox
			.split(",")
			.slice(0, 4)
			.map( (n, i) => (i % 2) ? Number(n) % 90 : Number(n) % 180 );

		if (options.bbox.some(n => isNaN(n))) {
			delete options.bbox;
		}
	}

	return options;
}

module.exports = async function (req, res, next) {

	const handler = req.params.featuretype == "point"
		? gis.project.raw.points
		: gis.project.raw.lines;

	const options = makeOptions(req.query);

	try {
		res.status(200).send(await handler(req.params.project, options));
		next();
	} catch (err) {
		next(err);
	}

};
