
const getPayloads = require('./payloads');
const despatchPayload = require('./despatch');
const {fetchItems, markFailed, markSent, rescheduleFailed} = require('./db');


function passed (result) {
	return "id" in result;
}

/**
 * Process the queue.
 *
 * Try to send up to a certain number of
 * items from the queue.
 * Reschedule any failed items.
 */
async function processQueue () {

	const items = await fetchItems({status: "queued"});
	for (const item of items) {
		const payloads = await getPayloads(item, (digestInfo) => {item.digest = digestInfo});
		const results = [];

		for (const {payload, digest} of payloads) {
			const response = await despatchPayload(payload);
			results.push({response, digest});
		}

		if (results.some(result => !passed(result.response))) {
			await markFailed(item, results);
		} else {
			await markSent(item, results);
		}
	}

	await rescheduleFailed(items);
}

module.exports = processQueue;

if (!module.parent) {
	processQueue().then(() => process.exit());
}
