const { exec } = require('child_process');

function openPort(port){
  return new Promise((resolve, reject) => {

    var callbackError = function(err) {
      port.removeListener('error', callbackError);
      port.removeListener('open', callbackError);

      reject(err.message);
    };

    var callbackOpen = function(data) {
      port.removeListener('error', callbackError);
      port.removeListener('open', callbackOpen);

      resolve("port open: ok");
    };

    port.on('error', callbackError);
    port.on('open', callbackOpen);

    port.open();

  })
}

function runSyncExec(command){
  return new Promise((resolve, reject) => {

    exec(command, (error, stdout, stderr) => {
      if(error == null) resolve(stdout);
      reject(error);
    });

  })
}

async function writeData(port, data, readbytes, timeout){
  return new Promise((resolve, reject) => {

    // If first item in data array is 255, we just write broadcast command to rsPort
    // We wait 3 seconds and resolve(["broadcast"])
    // It is important to resolve with array
    if(data[0] == 255) {

      port.write(Buffer.from(data), function(err) {
        if (err) {
          reject(err.message);
        }
      });

      setTimeout(resolve, 3000, ["broadcast"]);
      return;
    }

    //cmd-manager mame http route POST / terminal a tomu sa tiez nastavuje timeout!!!
    
    var callback = function(data) {
      rsPortReceivedData.push(...data);
      let l = rsPortReceivedData.length;

      if(l >= readbytes)
      {
        port.removeListener('data', callback);

        clearTimeout(t);
        resolve(rsPortReceivedData);
      }
    };

    port.removeListener('data', callback);

    let t = setTimeout(() => {
      port.removeListener('data', callback);

      //console.log("serialport helper: writeData TIMEOUT READING", rsPortReceivedData);

      reject("TIMEOUT READING");
    }, timeout);

    let rsPortReceivedData = [];

    port.on('data', callback);

    port.write(Buffer.from(data), function(err) {
      if (err) {
        port.removeListener('data', callback);
        reject(err.message);
      }

    });
  })
}

module.exports = {
  openPort,
  runSyncExec,
  writeData
}
