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

function parseValidity (row) {
	if (row.validity) {
		const rx = /^(.)("([\d :.+-]+)")?,("([\d :.+-]+)")?([\]\)])$/;
		const m = row.validity.match(rx);
		row.validity = [ m[1], m[3], m[5], m[6] ];
	}
	return row;
}

/**
 * Get an event from the database, with full history.
 */
async function get (projectId, eventId) {

	if (!projectId || !eventId) {
		throw {status: 400, message: "Invalid request" };
		return;
	}

	const client = await setSurvey(projectId);

	const text = `
		SELECT *
		FROM event_log_full
		WHERE id = $1;
	`;

	const res = await client.query(text, [eventId]);
	client.release();
	return res.rows.map(i => replaceMarkers(i) && parseValidity(i));
}

module.exports = get;
