
const { io: Client } = require("socket.io-client");

const express = require('express');
// const { createServer } = require('node:http');
// const { http } = require('node:http');
const http = require('node:http');
const { Server } = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = new Server(server);


const port = 3000



app.set('view engine', 'pug')
app.use(express.static('assets'))

app.get('/', (req, res) => {
  // res.send('Hello World!')
  res.render('index', { title: 'SGT', message: 'bonjour, je suis lucie et j`ai le syndorme de PUTe de la tourette!' })
})


// app.get('/speak', (req, res) => {
//   const text = req.query.text || message;
//   const command = `espeak "${text}"`;

//   exec(command, (error, stdout, stderr) => {
//     if (error) {
//       console.error(`Erreur lors de l'exécution de la commande : ${error}`);
//       return res.status(500).send('Erreur lors de la lecture du texte.');
//     }
//     res.send(`Texte lu : ${text}`);
//   });
// });


io.on('connection', (socket) => {
  console.log('Un utilisateur s\'est connecté');
  
  let stress = 0.1;
  setInterval(() => {
    stress += 0.1;
    socket.emit('stress', stress);
    console.log(stress);
  }, 2000);

  // Écoute les questions envoyées par le client
  socket.on('question', (question) => {
    console.log(`Question reçue: ${question}`);

    const options = {
      host: 'localhost',
      port: 5000,
      path: '/',
    };

    // Sending the request
    const req = http.request(options, (res) => {
      let data = ''

      res.on('data', (chunk) => {
          data += chunk;
          console.log('on data', data);
      });

      // Ending the response 
      res.on('end', () => {
          console.log('Body:', JSON.parse(data))
      });

    }).on("error", (err) => {
      console.log("Error: ", err)
    }).end()
  });

});

server.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

