var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var net = require('net');

var queue = []

app.get('*', function(req, res) {
    if ( req.url == '/' ) {
        res.sendFile(__dirname + '/visualization_server.html');
} else if ( req.url.match(/\.js$/) || req.url.match(/\.html$/) ) {
        res.sendFile(__dirname + req.url);
    }
});

io.on('connection', function(socket){
    console.log('A user connected!');
    
    socket.on('message', function(msg) {
        queue.push(msg);
    })
});

http.listen(9696, function() {
    console.log('Listening for user on port 9696');
});

// Create a server instance, and chain the listen function to it
// The function passed to net.createServer() becomes the event handler for the 'connection' event
// The sock object the callback function receives UNIQUE for each connection
net.createServer(function(sock) {
    
    // We have a connection - a socket object is assigned to the connection automatically
    console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);
    
    // Add a 'data' event handler to this instance of socket
    sock.on('data', function(data) {
        
        String(data).split('\n').forEach(function(entry) {
            if (entry != '') {
                io.emit('msg', entry);
            }
        })
        
    });
    
    // Add a 'close' event handler to this instance of socket
    sock.on('close', function(data) {
        console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);
    });
    
    sock.on('error', function(error) {
        console.log('ERROR: ');
    });
    
    setInterval(function() {
        while (true) {
            if (queue.length == 0) {
                break;
            }
            sock.write(queue.pop() + '\n');
        }
    }, 5)
    
}).listen(9999, '127.0.0.1');

console.log('Listening for simulator on localhost:9999');