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;
}

function transform (row) {
	if (row.validity[2]) {
		return {
			uid: row.uid,
			id: row.id,
			is_deleted: true
		}
	} else {
		row.is_deleted = false;
		row.has_edits = row.id != row.uid;
		row.modified_on = row.validity[1];
		delete row.uid;
		delete row.validity;
		return row;
	}
}

function unique (rows) {
	const o = {};
	rows.forEach(row => o[row.id] = row);
	return Object.values(o);
}

/**
 * Get the event change history from a given epoch (ts0),
 * for all events.
 */
async function changes (projectId, ts0, opts = {}) {

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

	const client = await setSurvey(projectId);

	const text = `
		SELECT *
		FROM event_log_changes($1);
	`;

	const res = await client.query(text, [ts0]);
	client.release();
	return opts.unique
		? unique(res.rows.map(i => transform(replaceMarkers(parseValidity(i)))))
		: res.rows.map(i => transform(replaceMarkers(parseValidity(i))));
}

module.exports = changes;
