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

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

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

	const sequence = opts.sequence && Number(opts.sequence) || null;
	const sequences = opts.sequences && (Array.isArray(opts.sequences)
		? opts.sequences.map(Number)
		: opts.sequences.split(/[^0-9]+/).map(Number)) || null;
	const date0 = opts.date0 ?? null;
	const date1 = opts.date1 ?? null;
	const jpq = opts.jpq || null; // jpq: JSONPath Query
	const label = opts.label ?? null;

	const text = `
		SELECT *
		FROM event_log e
		WHERE
			($1::numeric IS NULL OR sequence = $1) AND
			($2::numeric[] IS NULL OR sequence = ANY( $2 )) AND
			($3::timestamptz IS NULL OR
				(($4::timestamptz IS NULL AND date(tstamp) = $3) OR
					date(tstamp) BETWEEN SYMMETRIC $3 AND $4)) AND
			($5::jsonpath IS NULL OR jsonb_path_exists(meta::jsonb, $5::jsonpath)) AND
			($6::text IS NULL OR $6 = ANY(labels))
		ORDER BY ${sortKey} ${sortDir}
		LIMIT ${limit};
	`;

	const values = [ sequence, sequences, date0, date1, jpq, label ];

	const res = await client.query(text, values);
	client.release();
	return res.rows.map(i => replaceMarkers(i));
}

module.exports = list;
