

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

async function lines (options = {}) {

	const client = await pool.connect();

	const text = `
		SELECT json_build_object(
			'type', 'Feature',
			'geometry', ST_AsGeoJSON(ST_MakeLine(geometry))::json
		) geojson
		FROM (
			SELECT geometry
			FROM real_time_inputs
			WHERE
				($1 IS true
					AND geometry && ST_MakeEnvelope($2, $3, $4, $5, 4326)
				)
				OR ($1 IS false AND true)
			ORDER BY tstamp DESC
			LIMIT $6
		) t
	`;

// 	const values = [ options.limit || 1000, opts.offset || 0 ];
	const values = [
		"bbox" in options,
		...(options.bbox||[null, null, null, null]),
		options.limit || 5000
	];

	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};
	}
}

async function points (options = {}) {

	const client = await pool.connect();

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

	const text = `
		SELECT json_build_object(
			'type', 'Feature',
			'geometry', ST_AsGeoJSON(s.geometry)::json,
			'properties', s.meta
		) geojson
		FROM (
			SELECT geometry, meta
			FROM real_time_inputs
			WHERE
				($1 IS true
					AND geometry && ST_MakeEnvelope($2, $3, $4, $5, 4326)
				)
				OR ($1 IS false AND true)
			ORDER BY tstamp DESC
			LIMIT $6
		) s;
	`;

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

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

module.exports = {
	lines,
	points
};
