exports.id = 'nodesdb_change_check';
exports.title = 'Nodes DB change check';
exports.group = 'Worksys';
exports.color = '#888600';
exports.version = '1.0.2';
exports.icon = 'sign-out';
exports.input = 1;
exports.output = 1;
exports.readme = `Check, if nodes.table db changed compared to original database`;

const fs = require('fs');
const path = require('path');
const { sendNotification } = require('./helper/notification_reporter');
const nodesOriginalFile = path.join(__dirname, '../databases/nodes_original/', 'nodes_original.table');


exports.install = function(instance) {

    function compareArrays(array1, array2) {
      let message = "";
      let areEqual = true;
      let zmenene = []

      if (array1.length !== array2.length) {
        message += "Nezhoda v pocte nodov. "
      }

      const set1 = new Set(array1.map(obj => JSON.stringify(obj)));
      const set2 = new Set(array2.map(obj => JSON.stringify(obj)));

      for (const objStr of set1) {

        if (!set2.has(objStr)) {
          zmenene.push(objStr)
          areEqual = false;
        } else {
          set2.delete(objStr);
        }
      }

      if(!areEqual) {
          message += `Aktualne nody: ${zmenene.toString()}. Zmenene proti originalu: ${Array.from(set2).join(' ')}`;
          sendNotification("Nodesdb_changecheck", FLOW.GLOBALS.settings.rvoTbName, "nodes_db_changed", "", message, 0, instance);
      }
      else console.log("Arrays are equal.");

      console.log(message)
    }


    instance.on("data", _ => {

      let nodesData = FLOW.GLOBALS.nodesData;

      // we check if nodes.table has changed compared to nodes_original.table (we have array of nodes e.g. [{node:255, tbname: "agruhuwhgursuhgo34hgsdiguhrr"}]
      const nodes_actual = Object.keys(nodesData).map(node => ({[node]: nodesData[node].tbname}))
      let nodes_original = fs.readFileSync(nodesOriginalFile, { encoding: 'utf8', flag: 'r' });

      try {
        nodes_original = JSON.parse(nodes_original);
      } catch(e) {
        console.log(e)
      }


      setTimeout(() => compareArrays(nodes_actual, nodes_original),10000);
    })

}

