exports.id = 'infosender';
exports.title = 'Info sender';
exports.version = '1.0.0';
exports.group = 'Worksys';
exports.color = '#2134B0';
exports.input = 2;
exports.output = 1
exports.icon = 'bolt';

const { networkInterfaces } = require('os');

exports.html = `<div class="padding">
	<div class="row">
		<div class="col-md-6">
			<div data-jc="textbox" data-jc-path="edge" data-jc-config="placeholder:undefined;required:true" class="m">CSV Import</div>
		</div>
	</div>
</div>`;

exports.readme = `# send all data to projects.worksys.io, required to monitor status of controller(unipi)`;

exports.install = function(instance) {

  let id;
  let allValues = {};
  let sendAllValuesInterval;
  let configured = false;

  let now = new Date();
  console.log(exports.title, "INSTALLED", now.toLocaleString("sk-SK"));

  const nets = networkInterfaces();
  let ipAddresses = Object.create(null); // Or just '{}', an empty object

  for (const name of Object.keys(nets)) {
    for (const net of nets[name]) {
      // Skip over non-IPv4 and internal (i.e. 127.0.0.1) addresses
      if (net.family === 'IPv4' && !net.internal) {
        if (!ipAddresses[name]) {
          ipAddresses[name] = [];
        }
        ipAddresses[name].push(net.address);
      }
    }
  }

  function sendValues() {
    if (!configured) return;

    if (Object.keys(allValues).length > 0) {
      let dataToSend = { ...allValues };
      dataToSend.id = id;
      dataToSend.ipAddresses = ipAddresses;

      instance.send(0, dataToSend);

      allValues = {};
    }
  }

  instance.on("close", () => {
    clearInterval(sendAllValuesInterval);
  })

  instance.on("0", _ => {
    id = FLOW.GLOBALS.settings.project_id;
    if (id) configured = true;
    else console.log(exports.title, "InfoSender: Unable to send data, no id");
  })

  instance.on("1", flowdata => {
    allValues = { ...allValues, ...flowdata.data };
    //console.log("DATA RECEIVED", flowdata.data);
  })

  sendAllValuesInterval = setInterval(() => {
    sendValues();
  }, 60000 * 3);

}

