require("dotenv").config();
const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http, {
    cors: {
        origin: "*",
        methods: ["GET", "POST"]
    }
});
const port = process.env.NODE_PORT || 8780;
const cors = require('cors');

app.use(cors())

app.get('/read/:rfid', (req, res) => {
    console.log("Trigger by ID : " + req.params.rfid);
    io.emit('payload_channel', req.params.rfid); // This will emit the event to all connected sockets
    res.end();
});

io.on('connection', (socket) => {
    socket.on('connection', () =>{
        console.log(`Client Connected ID : ${socket.id}`);
    })

    socket.on('payload_channel', msg => {
        io.emit('payload_channel', msg);
    });
    socket.on('disconnect', () => {
        console.log('Client Disconnected');
    });
    socket.on("connect_error", (err) => {
        console.log(`Connect Error : ${err.message}`);
    });
});

http.listen(port, () => {
    console.log(`Socket.IO server running at http://localhost:${port}/`);
});