exports.id = 'db_init';
exports.title = 'DB Initialization';
exports.group = 'Worksys';
exports.color = '#888600';
exports.version = '1.0.2';
exports.icon = 'sign-out';
exports.output = 2;

exports.readme = `
  # DB initialization
`;

const { promisifyBuilder, makeMapFromDbResult } = require('./helper/db_helper.js');
const { initNotification } = require('./helper/notification_reporter');
const errorHandler = require('./helper/ErrorToServiceHandler');
const total_energy = require('../databases/total_energy');

const SEND_TO = {
	db_init: 0,
	infoSender: 1
};


exports.install = async function(instance) {
	const dbNodes = TABLE("nodes");
	const dbRelays = TABLE("relays");
	const dbSettings = TABLE("settings");
	const dbPins = TABLE("pins");
	const dbNotifications = TABLE("notifications");

	FLOW.GLOBALS = {};
	const dbs = FLOW.GLOBALS;

	const responseSettings = await promisifyBuilder(dbSettings.find());
	const responseNodes = await promisifyBuilder(dbNodes.find());
	const responsePins = await promisifyBuilder(dbPins.find());
	const responseRelays = await promisifyBuilder(dbRelays.find());
	const response = await promisifyBuilder(dbNotifications.find());

	dbs.pinsData = makeMapFromDbResult(responsePins, "pin");
	dbs.relaysData = makeMapFromDbResult(responseRelays, "line");
	dbs.nodesData = makeMapFromDbResult(responseNodes, "node");
	dbs.notificationsData = makeMapFromDbResult(response, "key");

	//+|354|nodesdata.....+|482|nodesdata....
	//for some reason, if last line in nodes.table is not empty, flow wrote more nodes data in one row,
	//so we have to add empty line at the bottom of nodes table to avoid this.
	//now, remove empty lines from nodesData database:
	if (dbs.nodesData.hasOwnProperty("0")) delete dbs.nodesData["0"];
	Object.keys(dbs.nodesData).forEach(node => dbs.nodesData[node].readout = {})

	let rvo_number = responseSettings[0]["rvo_name"].match(/\D+(\d{1,2})_/)[1];

	dbs.settings = {
		edge_fw_version: "2025-10-08",  //rok-mesiac-den
		language: responseSettings[0]["lang"],
		rvo_name: responseSettings[0]["rvo_name"],
		project_id: responseSettings[0]["project_id"],
		rvoTbName: dbs.relaysData[0]["tbname"],
		temperature_address: responseSettings[0]["temperature_address"],
		controller_type: responseSettings[0]["controller_type"],
		serial_port: responseSettings[0]["serial_port"],
		node_status_nok_time: responseSettings[0]["node_status_nok_time"] * 60 * 60 * 1000,// hour * minutes * 
		latitude: responseSettings[0]["latitude"],
		longitude: responseSettings[0]["longitude"],
		no_voltage: new Set(),//modbus_citysys - elektromer
		backup_on_failure: responseSettings[0]["backup_on_failure"],
		restore_from_backup: responseSettings[0]["restore_from_backup"],
		restore_backup_wait: responseSettings[0]["restore_backup_wait"],
		mqtt_host: responseSettings[0]["mqtt_host"],
		mqtt_clientid: responseSettings[0]["mqtt_clientid"],
		mqtt_username: responseSettings[0]["mqtt_username"],
		mqtt_port: responseSettings[0]["mqtt_port"],
		phases: responseSettings[0]["phases"],
		cloud_topic: responseSettings[0]["cloud_topic"],
		has_main_switch: responseSettings[0]["has_main_switch"],
		daily_report: responseSettings[0]["daily_report"],
		send_changed_node_numbers: responseSettings[0]["send_changed_node_numbers"],
		rvo_number: rvo_number,

		//dynamic values
		masterNodeIsResponding: true, //cmd_manager
		maintenance_mode: false,
	}


	dbs.settings.energy_to_switch_lamps = total_energy[rvo_number];
	if (dbs.settings.energy_to_switch_lamps === undefined) console.log('=============== db_init.js: energy_to_switch_lamps is undefined');

	FLOW.dbLoaded = true;
	errorHandler.setProjectId(dbs.settings.project_id);
	initNotification();

	//APP START - send to data services
	const toService = {
		id: dbs.settings.project_id,
		name: dbs.settings.rvo_name,
		fw_version: dbs.settings.edge_fw_version,
		startdate: new Date().toISOString().slice(0, 19).replace('T', ' '),
		js_error: "",
		error_message: ""
	};

	instance.send(SEND_TO.infoSender, toService);
	console.log("----------------> START - message send to service", toService);

	setTimeout(() => {
		console.log("DB_INIT - data loaded");
		instance.send(SEND_TO.db_init, "_")
	}, 5000)

};

