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

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

	const text = `
		SELECT *
		FROM sequences_summary
		WHERE sequence = $1;
	`;

	const res = await client.query(text, [sequence]);
	client.release();

	return res.rows[0];
}


async function get (projectId, sequence, opts = {}) {
	if (opts.summary) {
		return await getSummary(projectId, sequence, opts);
	}

	const client = await setSurvey(projectId);

	const sortFields = [
		"sequence", "sailline", "line", "point", "tstamp"
	];
	const sortKey = opts.sortBy && sortFields.includes(opts.sortBy) && opts.sortBy || "tstamp";
	const sortDir = opts.sortDesc == "false" ? "ASC" : "DESC";
	const offset = Math.abs(opts.offset) || Math.abs((opts.page-1)*opts.itemsPerPage) || 0;
	const limit = Math.abs(opts.limit) || Math.abs(Number(opts.itemsPerPage)) || null;

	const restriction = sequence
		? "sequence = $3"
		: "TRUE OR $3";

	const text = `
		SELECT
			sequence, sailline, line, point, tstamp,
			objRefRaw, objRefFinal,
			geometryPreplot::json,
			geometryRaw::json,
			geometryFinal::json,
			errorRaw::json,
			errorFinal::json,
			jsonb_path_query(meta::jsonb, $4) as meta
		FROM sequences_detail
		WHERE ${restriction}
		ORDER BY ${sortKey} ${sortDir}
		OFFSET $1
		LIMIT $2;
	`;

	const values = [offset, limit, sequence, opts.path || "$"];
	const res = await client.query(text, values);
	client.release();

	if (opts.project) {
		const tokens = opts.project.split(/\s*[,;:\s]\s*/).filter(e => e.length);
		const project = tokens.map(i => i.replace(/^([^.]+)\..*$/, "$1"));
		return res.rows.map( r =>
			Object.fromEntries(Object.entries(r).filter(entry => project.includes(entry[0])))
		);
	} else {
		return res.rows;
	}
}

module.exports = get;
