exports.id = 'thermometer';
exports.title = 'Thermometer';
exports.group = 'Worksys';
exports.color = '#5CB36D';
exports.input = 1;
exports.version = '1.0.3';
exports.output = ["red", "white", "blue"];
exports.icon = 'thermometer-three-quarters';

exports.readme = `# Getting temperature values for RVO. In case of LM, you need device address. In case of unipi, evok sends values, in case thermometer is installed`;

const { errLogger, logger, monitor } = require('./helper/logger');

const SEND_TO = {
  debug: 0,
  tb: 1,
  dido_controller: 2
}

//read temperature - frequency
let timeoutMin = 5;//minutes
let NUMBER_OF_FAILURES_TO_SEND_ERROR = 13;

exports.install = function(instance) {

  const { exec } = require('child_process');
  const { sendNotification } = require('./helper/notification_reporter');

  let startRead;
  let counter = 0;
  let rvoTbName = "";
  let temperatureAddress = "";

  logger.debug(exports.title, "installed");

  instance.on("close", function(){
    clearInterval(startRead);
  })


  const main = function() {

    try {

      if(temperatureAddress === "") throw "Thermometer: temperatureAddress is not defined";

      exec(`owread -C ${temperatureAddress}/temperature`, (error, stdout, stderr) => {

        if(!error) 
        {
          parseData(stdout)
          return;
        }

        counter++;
        if(counter == NUMBER_OF_FAILURES_TO_SEND_ERROR) sendNotification("Thermometer_main", rvoTbName, "thermometer_is_not_responding", {}, {"Error": error}, SEND_TO.tb, instance, "thermometer");
        monitor.info("Thermometer is not responding", error);
        instance.send(SEND_TO.dido_controller, {status: "NOK-thermometer"});
      });

    }
    catch(err) {
      errLogger.error(exports.title, err);
      clearInterval(startRead);
    }
  }

  const parseData = function(data) {

    data = parseFloat(data);
    //logger.debug("Thermometer", data);

    if(isNaN(data)) {
      errLogger.error("Thermometer sends invalid data");
      return;
    }

    if(counter > NUMBER_OF_FAILURES_TO_SEND_ERROR) //1 hour
    {
      instance.send(SEND_TO.debug, "Thermometer - temperature data are comming again");
      sendNotification("Thermometer_parseData", rvoTbName, "thermometer_is_responding_again", {}, "", SEND_TO.tb, instance, "thermometer");
    }

    const values = {
      "temperature": Number(data.toFixed(2)),
    }

    instance.send(SEND_TO.dido_controller, {values: values});
    counter = 0;
  }

  instance.on("data", _ => {
    temperatureAddress = FLOW.GLOBALS.settings.temperature_address;
    rvoTbName = FLOW.GLOBALS.settings.rvoTbName;
    startRead = setInterval(main, timeoutMin * 1000 * 60);
    setTimeout(main, 20000);
  })
};
