

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

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

	const client = await setSurvey(projectId);

	const text = `
		SELECT ST_AsGeoJSON(s.*) geojson
		FROM (
			SELECT
				rlsg.*, date_trunc('second', rlsg.duration) AS duration
			FROM raw_lines_summary_geometry rlsg
		) 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.*, 'geometry') geojson, ST_AsGeoJSON(t.delta_geom) delta
		FROM (
			SELECT rl.line sailline, rs.line, rs.point, sequence, objref, tstamp, ST_Transform(rs.geometry, 4326) geometry,
				ST_Transform(ST_MakeLine(pp.geometry, rs.geometry), 4326) delta_geom
			FROM raw_lines rl
			INNER JOIN raw_shots rs USING (sequence)
			LEFT JOIN preplot_points pp ON rs.line = pp.line AND rs.point = pp.point
			WHERE
				($1 IS true
					AND ST_Transform(rs.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),
			JSON.parse(r.delta)
		]).flat().filter(i => i != null);
	} else {
		throw {status: 404};
	}
}

module.exports = {
	lines,
	points
};
