exports.id = 'db_init';
exports.title = 'DB Initialization';
exports.group = 'Worksys';
exports.color = '#888600';
exports.version = '1.0.2';
exports.icon = 'sign-out';
exports.input = 1;
exports.output = ["blue"];

exports.html = `<div class="padding">
	<div class="row">
		<div class="col-md-6">
			<div data-jc="textbox" data-jc-path="host" data-jc-config="placeholder:test.mosquitto.org;required:false" class="m">Hostname or IP address (if not empty - setting will override db setting)</div>
		</div>
		<div class="col-md-6">
			<div data-jc="textbox" data-jc-path="port" data-jc-config="placeholder:1883;required:true" class="m">Port</div>
		</div>
	</div>
	<div class="row">
		<div class="col-md-6">
			<div data-jc="textbox" data-jc-path="clientid">@(Client id)</div>
		</div>
		<div class="col-md-6">
			<div data-jc="textbox" data-jc-path="username" class="m">@(Username)</div>		
		</div>
	</div>
</div>`;


exports.readme = `
# DB initialization
`;

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


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"];

  dbs.settings = {
    edge_fw_version : "2025-01-09",  //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"],
  
    //dynamic values
    masterNodeIsResponding : true, //cmd_manager
    maintenance_mode : false,
  } 

  FLOW.dbLoaded = true;
  initNotification();

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

};  




