const vm = require('vm');
const { project, sequence, configuration, info } = require('../../db')


/** Run sequence QCs for project
 *
 * @a projectId The project in which to run the QCs
 * @a definitions The QC definitions, as a flat array
 * @a parameters The QC parameters (variables)
 *
 * @a return results array
 */
async function runSequenceQCs (projectId, definitions, parameters) {
	console.log("runSequenceQCs", projectId);

	const results = {}; // The structure will be { sequence: { qc_id: test_result } }

	const sequences = await sequence.list(projectId, {missing:true});
	for (const currentItem of sequences) {
		const sequenceNumber = currentItem.sequence;
		currentItem._ = (k) => k.split(".").reduce((a, b) => typeof a != "undefined" ? a[b] : a, currentItem);

		// These two objects are passed to runInNewContext so that they are
		// available to the QC functions
		const shotpoints = await sequence.get(projectId, sequenceNumber);
		const missingShotpoints = currentItem.fsp_final && currentItem.lsp_final
			? currentItem.missing_final
			: currentItem.missing_raw;

		// Let us run QCs
		for (qc of definitions.filter(i => i.iterate == "sequences")) {
			if (!qc.disabled) {
				console.log("CURRENT ITEM", sequenceNumber, qc.id);

				const variables = { shotpoints, missingShotpoints };
				const ctx = {...variables, currentItem, parameters};
				const res = vm.runInNewContext(qc.check, ctx);

				console.log("COMING OUT", res);
				if (!(sequenceNumber in results)) {
					results[sequenceNumber] = {};
				}
				results[sequenceNumber][qc.id] = res === true ? res : {
					remarks: (typeof res === "string" ? res : res.remarks),
					shots: res.shots,
					labels: qc.labels
				};

			}
		}

		for (qc of definitions.filter(i => i.iterate == "sequences")) {
			if (qc.ignoreAllFailed) {
				const allFailed = Object.values(results).map(i => i[qc.id]).every(i => i !== true);
				if (allFailed) {
					console.log("IGNORING ALL FAILED", qc.id);
					for (const sequenceNumber in results) {
						delete results[sequenceNumber][qc.id];
					}
				}
			}
		}
	}

	return results;
}

module.exports = runSequenceQCs;
