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

class DetectSOLEOL {

	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");
			// DEBUG("%j", data);
			const cur = data?.payload?.new?.meta;
			const prev = this.prev?.payload?.new?.meta;
			const sequence = Number(cur._sequence);

			// DEBUG("%j", prev);
			// DEBUG("%j", cur);
			DEBUG("prv.lineName: %s\ncur.lineName: %s\nprv._sequence: %s\ncur._sequence: %s\nprv.lineStatus: %s\ncur.lineStatus: %s", prev.lineName, cur.lineName, prev._sequence, cur._sequence, prev.lineStatus, cur.lineStatus);

			if (prev.lineName == cur.lineName && prev._sequence == cur._sequence &&
				prev.lineStatus != "online" && cur.lineStatus == "online" && sequence) {
				INFO("Transition to ONLINE detected");

				// We must use schema2pid because the pid may not have been
				// populated for this event.
				const projectId = await ctx.schema2pid(cur._schema ?? prev._schema);
				const labels = ["FSP", "FGSP"];
				const remarks = `SEQ ${cur._sequence}, SOL ${cur.lineName}, BSP: ${(cur.speed*3.6/1.852).toFixed(1)} kt, Water depth: ${Number(cur.waterDepth).toFixed(0)} m.`;
				const payload = {
					type: "sequence",
					sequence,
					point: cur._point,
					remarks,
					labels,
					meta: {auto: true, author: `*${this.constructor.name}*`}
				}
				INFO("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 (prev.lineName == cur.lineName && prev._sequence == cur._sequence &&
				prev.lineStatus == "online" && cur.lineStatus != "online" && sequence) {
				INFO("Transition to OFFLINE detected");

				const projectId = await ctx.schema2pid(prev._schema ?? cur._schema);
				const labels = ["LSP", "LGSP"];
				const remarks = `SEQ ${prev._sequence}, EOL ${prev.lineName}, BSP: ${(prev.speed*3.6/1.852).toFixed(1)} kt, Water depth: ${Number(prev.waterDepth).toFixed(0)} m.`;
				const payload = {
					type: "sequence",
					sequence,
					point: prev._point,
					remarks,
					labels,
					meta: {auto: true, author: `*${this.constructor.name}*`}
				}
				INFO("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 = DetectSOLEOL;
