const { setSurvey, transaction } = require('../../db/connection')

async function saveShotsQC (projectId, results) {

	const client = await setSurvey(projectId);
	await transaction.begin(client);

	async function deleteQCEvents (sequence) {
		const text = `
			DELETE
			FROM event_log_full
			WHERE sequence = $1 AND meta ? 'qc_id';
		`;

		const values = [ sequence ];

		return await client.query(text, values);
	}

	async function updateQCEvent (sequence, shot, qc_id, result) {
		const text = `
			INSERT INTO event_log (sequence, point, remarks, labels, meta)
			SELECT $1, $2, $4, $5, $6
			WHERE NOT EXISTS (
				SELECT 1 FROM event_log WHERE sequence = $1 AND point = $2 AND meta->>'qc_id' = $3
			);
		`;

// 		console.log("INSERT QUERY", projectId, sequence, shot, qc_id, result);
		const values = [ sequence, shot, qc_id, result.remarks, result.labels, {qc_id, readonly: true} ];

		await client.query(text, values);
	};

	for (const sequence in results) {
		// Remove *all* QC events for this sequence
		await deleteQCEvents(sequence);
		for (const shot in results[sequence]) {
			for (const qc_id in results[sequence][shot]) {
				const result = results[sequence][shot][qc_id];
				if (result !== true) { // `true` means QC passed. Otherwise expect string or array.
					// Add or replace an existing event for this QC
					await updateQCEvent(sequence, shot, qc_id, result);
				}
			}
		}
		console.log("Done sequence", sequence);
	}

	await transaction.commit(client);
	await client.release();

}

module.exports = saveShotsQC;
