const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http, {
    serveClient: false,
    // transports: ['websocket'],
    pingInterval: 8000
});
var udp = require('dgram');

var lonet2_server = udp.createSocket('udp4');


io.on('connection', (socket) => {
  console.log('a user connected');
  
  socket.on('connectReport', (data) => {
	  var cam = data.cam;
    var num = data.num;
    var type = data.type;
		data.type = "connectReport";
    data.id = socket.id;

    lonet2_server.send(JSON.stringify(data), 3002, "localhost", function (error) {
      if (error) {
          client.close();
          console.log(error);
      }
  });

		console.log(data.cam);
		console.log(data.num);
		console.log(data.type);
    console.log(data.id);
  })

  socket.on('encoderReport', (data) => { //Sent from hub with all encoder values

    var encoderJson = {type: "encoderReport"};
    encoderJson.id = socket.id;
    encoderJson.value = data;
    lonet2_server.send(JSON.stringify(encoderJson), 3002, "127.0.0.1", function (error) {
      if (error) {
          client.close();
      }
  });
    //console.log(encoderJson);
  })


});


http.listen(3000, () => {
  console.log('listening on *:3000');
});


// emits when any error occurs
lonet2_server.on('error', function (error) {
 // console.log('Error: ' + error);
  lonet2_server.close();
});

// emits on new datagram msg
lonet2_server.on('message', function (msg, info) {
 // var jsonMsg = msg.toJSON();
  let jsonMsg = JSON.parse(msg.toString());
 // console.log('Data received from client : ' + msg.toString());
 // console.log('Received %d bytes from %s:%d\n', msg.length, info.address, info.port);
  io.to(jsonMsg.id).emit(jsonMsg.type, jsonMsg);
 
});

//emits when socket is ready and listening for datagram msgs
lonet2_server.on('listening', function () {
  var address = lonet2_server.address();
  var port = address.port;
  var family = address.family;
  var ipaddr = address.address;
  console.log('Server is listening at port' + port);
  console.log('Server ip :' + ipaddr);
  console.log('Server is IP4/IP6 : ' + family);
});

lonet2_server.bind(3003);


