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

class DetectProjectConfigurationChange {

	author = `*${this.constructor.name}*`;

	constructor (ctx) {
		DEBUG(`${this.author} instantiated`);

		// Grab project configurations.
		// NOTE that this will run asynchronously
		//this.run({channel: "project"}, ctx);
	}

	async run (data, ctx) {

		if (!data || data.channel !== "project") {
			return;
		}

		// Project notifications, as of this writing, most likely
		// do not carry payloads as those exceed the notification
		// size limit.
		// For our purposes, we do not care as we just re-read all
		// the configurations for all non-archived projects.

		try {
			DEBUG("Project configuration change detected")

			const projects = await ctx.db.project.get();
			ctx.db.project.organisations.setCache(projects);

			const _ctx_data = {};
			for (let pid of projects.map(i => i.pid)) {
				DEBUG("Retrieving configuration for", pid);
				const cfg = await ctx.db.project.configuration.get(pid);
				if (cfg?.archived === true) {
					DEBUG(pid, "is archived. Ignoring");
					continue;
				}

				DEBUG("Saving configuration for", pid);
				_ctx_data[pid] = cfg;
			}

			if (! ("projects" in ctx)) {
				ctx.projects = {};
			}

			ctx.projects.configuration = _ctx_data;
			DEBUG("Committed project configuration to ctx.projects.configuration");

		} catch (err) {
			DEBUG(`${this.author} error`, err);
			throw err;
		}
	}
}

module.exports = DetectProjectConfigurationChange;
