const { schema2pid } = require('../../lib/db/connection');
const { event } = require('../../lib/db');
const { ALERT, ERROR, INFO, DEBUG } = require('DOUGAL_ROOT/debug')(__filename);

/** Midnight shot detection.
 *
 * This event handler checks if there is an UTC date jump between consecutive
 * shots. If a jump is detected, it sends to new entries to the event log, for
 * the last shot and first shot of the previous and current dates, respectively.
 */
class DetectFDSP {

	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;
			const sequence = Number(cur._sequence);

			if (this.prev.lineName == cur.lineName && this.prev._sequence == cur._sequence &&
				this.prev.lineStatus == "online" && cur.lineStatus == "online" && sequence) {

				if (this.prev.time.substr(0, 10) != cur.time.substr(0, 10)) {
					// Possibly a date change, but could also be a missing timestamp
					// or something else.

					const ts0 = new Date(this.prev.time)
					const ts1 = new Date(cur.time);

					if (!isNaN(ts0) && !isNaN(ts1) &&  ts0.getUTCDay() != ts1.getUTCDay()) {
						INFO("Sequence shot across midnight UTC detected", cur._sequence, cur.lineName);

						const ldsp = {
							sequence: this.prev._sequence,
							point: this.prev._point,
							remarks: "Last shotpoint of the day",
							labels: ["LDSP", "Prod"],
							meta: {auto: true, author: `*${this.constructor.name}*`}
						};

						const fdsp = {
							sequence: cur._sequence,
							point: cur._point,
							remarks: "First shotpoint of the day",
							labels: ["FDSP", "Prod"],
							meta: {auto: true, author: `*${this.constructor.name}*`}
						};

						INFO("LDSP", ldsp);
						INFO("FDSP", fdsp);

						const projectId = await schema2pid(this.prev._schema);

						if (projectId) {
							await event.post(projectId, ldsp);
							await event.post(projectId, fdsp);
						} else {
							ERROR("projectId not found for", this.prev._schema);
						}
					} else {
						WARNING("False positive on these timestamps", this.prev.time, cur.time);
						WARNING("No events were created");
					}
				}

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

module.exports = DetectFDSP;
