

const { setSurvey } = require('../../connection');

async function lines (projectId) {

	const client = await setSurvey(projectId);

	const text = `
		SELECT ST_AsGeoJSON(s.*) geojson
		FROM (
			SELECT
				flsg.*, date_trunc('second', flsg.duration) AS duration
			FROM final_lines_summary_geometry flsg
		) s;
	`;

	const res = await client.query(text);
	client.release();

	if (res.rows && res.rows.length) {
		return res.rows.map(r => JSON.parse(r.geojson));
	} else {
		throw {status: 404};
	}
}

async function points (projectId, options = {}) {

	const client = await setSurvey(projectId);

	const values = [
		"bbox" in options,
		...(options.bbox||[null, null, null, null]),
		options.limit || 5000
	];

	const text = `
		SELECT ST_AsGeoJSON(t.*) geojson
		FROM (
			SELECT fl.line sailline, fs.line, point, sequence, objref, tstamp, ST_Transform(geometry, 4326) geometry
			FROM final_lines fl
			INNER JOIN final_shots fs USING (sequence)
			WHERE
				($1 IS true
					AND ST_Transform(geometry, 4326) && ST_MakeEnvelope($2, $3, $4, $5, 4326)
				)
				OR ($1 IS false AND true)
			LIMIT $6
		) t
	`;

	const res = await client.query(text, values);
	client.release();

	if (res.rows && res.rows.length) {
		return res.rows.map(r => JSON.parse(r.geojson));
	} else {
		throw {status: 404};
	}
}

module.exports = {
	lines,
	points
};

