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

function init () {
	const iids = [];

	async function start () {
		INFO("Initialising %d periodic tasks", tasks.length);
		for (let t of tasks) {
			const fn = t.init ? await t.init() : t.task;
			const iid = setInterval(fn, t.timeout);
			iids.push(iid);
		}
		return iids;
	};

	function stop () {
		INFO("Stopping %d periodic tasks", iids.length);
		for (let iid of iids) {
			clearInterval(iid);
		}
	}

	async function cleanup () {
		stop();
		DEBUG("Cleaning up %d periodic tasks", tasks.length);
		for (let t of tasks) {
			if (t.cleanup) {
				await t.cleanup();
			}
		}
	}

	return { start, stop, cleanup, iids };
}

module.exports = {
	init
};
