const { ALERT, ERROR, WARNING, NOTICE, INFO, DEBUG } = require('DOUGAL_ROOT/debug')(__filename);

const Handlers = [
	require('./detect-project-configuration-change'),
	require('./detect-soleol'),
	require('./detect-soft-start'),
	require('./report-line-change-time'),
	require('./detect-fdsp')
];

function init (ctx) {

	const instances = Handlers.map(Handler => new Handler(ctx));

	function prepare (data, ctx) {
		const promises = [];
		for (let instance of instances) {
			const promise = new Promise(async (resolve, reject) => {
				try {
					DEBUG("Run", instance.author);
					const result = await instance.run(data, ctx);
					DEBUG("%s result: %O", instance.author, result);
					resolve(result);
				} catch (err) {
					ERROR("%s error:\n%O", instance.author, err);
					reject(err);
				}
			});
			promises.push(promise);
		}
		return promises;
	}

	function despatch (data, ctx) {
		return Promise.allSettled(prepare(data, ctx));
	}

	return { instances, prepare, despatch };
}

module.exports = {
	Handlers,
	init
};
