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

async function list (projectId, opts = {}) {
	const client = await setSurvey(projectId);

	const sortFields = [ "line", "length", "azimuth", "fsp", "lsp", "num_points", "incr", "remarks" ];
	const sortKey = opts.sortBy && sortFields.includes(opts.sortBy) && opts.sortBy || "line";
	const sortDir = opts.sortDesc == "true" ? "DESC" : "ASC";
	const offset = Math.abs((opts.page-1)*opts.itemsPerPage) || 0;
	const limit = Math.abs(Number(opts.itemsPerPage)) || null;

	// FIXME Move this into the database as a view or something
	const text = `
		WITH counts AS (
			SELECT pls.*, COALESCE(ppc.virgin, 0) na, COALESCE(ppc.tba, 0) tba
			FROM preplot_lines_summary pls
			LEFT JOIN (
				SELECT line, COUNT(*) virgin, COUNT(NULLIF(ntba,true)) tba
				FROM preplot_points_count pc
				INNER JOIN preplot_points pp
					USING (line, point)
				WHERE pc.count = 0
				GROUP BY line
			) ppc
				USING (line)
		)
		SELECT s.*, pl.ntba, c.na, c.tba, pl.meta
		FROM preplot_lines_summary s
		INNER JOIN preplot_lines pl ON pl.class = 'V' AND s.line = pl.line
		LEFT JOIN counts c ON s.line = c.line
		ORDER BY ${sortKey} ${sortDir}
		OFFSET $1
		LIMIT $2;
	`;

	const res = await client.query(text, [offset, limit]);
	client.release();
	return res.rows;
}

module.exports = list;
