const parsers = require('./parsers');
var SerialPort = require('serialport');
// const Readline = require('@serialport/parser-readline');

const subscribers = [];

let connected = false;
// var interval = setInterval(() => {

//   if(!connected) {
//     var serialPort = new SerialPort(
//       //'/dev/tty.SLAB_USBtoUART',
//       '/dev/ttyUSB0',
//       {
//         baudRate: 115200,
//       },
//       false
//     );
//     serialPort.on('error', function (err) {
//       console.log(err); // THIS SHOULD WORK!
//     });
    
//     serialPort.on("open", function () {
//       sendStartupEvents()
//       console.log('open');
//       const usbParser = serialPort.pipe(new Readline({ delimiter: '\r\n' }));
      

//       usbParser.on('data', (data) => {
//         let parsedData = parsers.aim.parse(data, false);
//         if (parsedData.length === 0) {
//           parsedData = parsers.obd2.parse(data);
    
//           if (parsedData.value !== undefined) {
//             sendDataToSubscribers(parsedData);
//           }
//         } else {
//           parsedData.forEach((data) => {
//             if (data.value !== undefined) {
//               sendDataToSubscribers(data);
//             }
//           });
//         }
//       });
//     });
//   } else {
//     clearInterval(interval);
//   }
// }, 1000);



const sendDataToSubscribers = (data) => {
  subscribers.forEach((callback) => {
    if (typeof callback === 'function') callback(data);
  });
};

const sendStartupEvents = () => {
  let data = {
    value: 8000,
    name: "rpm",
    mode: undefined,
    pid: undefined,
    min: 0,
    max: 10000,
    unit: undefined,
    topic: undefined,
  }
  sendDataToSubscribers(data)
  data = {
    value: 2000,
    name: "rpm",
    mode: undefined,
    pid: undefined,
    min: 0,
    max: 10000,
    unit: undefined,
    topic: undefined,
  }
  sendDataToSubscribers(data)
  data = {
    value: 6000,
    name: "rpm",
    mode: undefined,
    pid: undefined,
    min: 0,
    max: 10000,
    unit: undefined,
    topic: undefined,
  }
  sendDataToSubscribers(data)
  data = {
    value: 0,
    name: "rpm",
    mode: undefined,
    pid: undefined,
    min: 0,
    max: 10000,
    unit: undefined,
    topic: undefined,
  }
  sendDataToSubscribers(data)
}

const subscribe = (callback) => {
  subscribers.push(callback);
};

module.exports = { subscribe };
