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

class DetectSoftStart {

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

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

	async run (data, ctx) {

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

		if (!(data.payload && data.payload.new && data.payload.new.meta)) {
			return;
		}

		if (!this.prev) {
			DEBUG("Initialising `prev`");
			this.prev = data;
			return;
		}

		try {
			DEBUG("Running");
			const cur = data?.payload?.new?.meta;
			const prev = this.prev?.payload?.new?.meta;
			// DEBUG("%j", prev);
			// DEBUG("%j", cur);
			if (cur.lineStatus == "online" || prev.lineStatus == "online") {
				DEBUG("lineStatus is online, assuming not in a soft start situation");
				return;
			}

			DEBUG("cur.num_guns: %d\ncur.num_active: %d\nprv.num_active: %d\ncur.num_nofire: %d\nprev.num_nofire: %d", cur.num_guns, cur.num_active, prev.num_active, cur.num_nofire, prev.num_nofire);


			if (cur.num_active >= 1 && !prev.num_active && cur.num_active < cur.num_guns) {
				INFO("Soft start detected @", cur.tstamp);

				// FIXME Shouldn't need to use schema2pid as pid already present in payload.
				const projectId = await ctx.schema2pid(cur._schema ?? prev._schema);

				// TODO: Try and grab the corresponding comment from the configuration?
				const payload = {
					tstamp: cur.tstamp,
					remarks: "Soft start",
					labels: [ "Daily", "Guns", "Prod" ],
					meta: {auto: true, author: `*${this.constructor.name}*`}
				};
				DEBUG("Posting event", projectId, payload);
				if (ctx.dryRun) {
					DEBUG(`DRY RUN: await ctx.db.event.post(${projectId}, ${payload});`);
				} else {
					await ctx.db.event.post(projectId, payload);
				}

			} else if ((cur.num_active == cur.num_guns || (prev.num_nofire > 0 && cur.num_nofire == 0)) && prev.num_active < cur.num_active) {
				INFO("Full volume detected @", cur.tstamp);

				const projectId = await ctx.schema2pid(cur._schema ?? prev._schema);

				// TODO: Try and grab the corresponding comment from the configuration?
				const payload = {
					tstamp: cur.tstamp,
					remarks: "Full volume",
					labels: [ "Daily", "Guns", "Prod" ],
					meta: {auto: true, author: `*${this.constructor.name}*`}
				};
				DEBUG("Posting event", projectId, payload);
				if (ctx.dryRun) {
					DEBUG(`DRY RUN: await ctx.db.event.post(${projectId}, ${payload});`);
				} else {
					await ctx.db.event.post(projectId, payload);
				}
			}

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

module.exports = DetectSoftStart;
