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

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

	const client = await setSurvey(projectId);

	const values = [
		"bbox" in options,
		...(options.bbox||[null, null, null, null]),
		options.limit || 5000,
		["V", "S"].includes(options.class) && options.class || "S"
	];

	const text = values[6] == 'V'
		? `
			SELECT json_build_object(
				'type', 'FeatureCollection',
				'features', json_agg(geojson::json)) geojson
			FROM (
				SELECT ST_AsGeoJSON(t.*) geojson
				FROM (
					SELECT pl.line, psl.incr, psl.remarks, psl.ntba, ST_Transform(pl.geometry, 4326) geometry
					FROM preplot_lines pl
					INNER JOIN preplot_saillines psl
						ON pl.line = psl.sailline
					WHERE
						class = $7
						AND (
							($1 IS true
								AND ST_Transform(pl.geometry, 4326) && ST_MakeEnvelope($2, $3, $4, $5, 4326)
							)
							OR ($1 IS false AND true)
						)
					LIMIT $6
				) t
			) f;
		`
		: `
			SELECT json_build_object(
				'type', 'FeatureCollection',
				'features', json_agg(geojson::json)) geojson
			FROM (
				SELECT ST_AsGeoJSON(t.*) geojson
				FROM (
					SELECT pl.line, psl.incr, psl.remarks, psl.ntba, ST_Transform(pl.geometry, 4326) geometry
					FROM preplot_lines pl
					INNER JOIN preplot_saillines psl
						ON pl.line = psl.line
					WHERE
						class = $7
						AND (
							($1 IS true
								AND ST_Transform(pl.geometry, 4326) && ST_MakeEnvelope($2, $3, $4, $5, 4326)
							)
							OR ($1 IS false AND true)
						)
					LIMIT $6
				) t
			) f;
		`

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

	if (res.rows && res.rows.length) {
		return res.rows[0].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,
		["V", "S"].includes(options.class) && options.class || "S"
	];

	const text = `
		SELECT json_build_object(
			'type', 'FeatureCollection',
			'features', json_agg(geojson::json)) geojson
		FROM (
			SELECT ST_AsGeoJSON(t.*) geojson
			FROM (
				SELECT line, point, class, ntba, ST_Transform(geometry, 4326) geometry
				FROM preplot_points
				WHERE
					class = $7
					AND (
						($1 IS true
							AND ST_Transform(geometry, 4326) && ST_MakeEnvelope($2, $3, $4, $5, 4326)
						)
						OR ($1 IS false AND true)
					)
				LIMIT $6
			) t
		) f;
	`;

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

	if (res.rows && res.rows.length) {
		return res.rows[0].geojson;
	} else {
		throw {status: 404};
	}
}

module.exports = {
	lines,
	points
};
