// Importing Libraries Needed
require('dotenv').config();
const { SerialPort } = require('serialport');
const { ReadlineParser } = require('@serialport/parser-readline');
const axios = require('axios');
const mySerialPort = new SerialPort({
    path: '/dev/ttyUSB0',
    baudRate: 115200,
    autoOpen: false,
    parity: 'none',
    stopBits: 1,
    dataBits: 8,
    flowControl: false
})
const parser = mySerialPort.pipe(new ReadlineParser({ delimiter: '\r\n' }));

mySerialPort.open(function (error) {
    if (error) {
        console.log('failed to open: ' + error);
    } else {
        console.log('serial port opened');
        parser.on('data', (stream) => {
            // console.log(stream);     
            // If Tag is placed on Sensor we will check the TD
            if (stream.includes("TD")) {
                console.log(`Reading RFID : ${stream}`);
                let cleanedStream = stream.slice(13, 27);

                axios.get(`${process.env.HIVE_CMS_SERVER}/api/tagdetails/${cleanedStream}`)
                    .then((result) => {
                        console.log(result.data);
                    }).catch((error) => {
                        console.log(error.msg);
                    })


                axios.get(`${process.env.SOCKETIO_SERVER}/read/${cleanedStream}`).then(() => {
                    console.log("Sent To Socket Service : " + cleanedStream);
                }).catch((error) => {
                    console.log(error.msg);
                })

            }
        });
        mySerialPort.on('error', function (data) {
            console.log('Error: ' + data);
        })
    }
});

