/**
 * Module dependencies.
 */

var _express = require('express');
var _routes = require('./routes');
var _notifications = require('./routes/notifications');
var _http = require('http');
var _path = require('path');
var _io = require('socket.io');
var _redis = require('redis');
var _httpProxy = require('http-proxy');

var app = _express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', _path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(_express.favicon());
app.use(_express.logger('dev'));
app.use(_express.json());
app.use(_express.urlencoded());
app.use(_express.methodOverride());
app.use(app.router);
app.use(_express.static(_path.join(__dirname, 'public')));

// development only
if ('development' === app.get('env')) {
  app.use(_express.errorHandler());
}

var server = _http.createServer(app);
var io = _io.listen(server);
var proxy = _httpProxy.createProxyServer();

function pythonProxy(req, res) {
  console.log("Proxying request...");
  proxy.web(req, res, {
    target : 'http://localhost:3010'
  }, function(e) {
    console.log("err: " + e);
    var respondeBody = 'ERROR: ' + e;
    res.writeHead(200, {
      'Content-Length' : respondeBody.length,
      'Content-Type' : 'text/plain'
    });
    res.end(respondeBody);
  });
}

// map urls
app.get('/', _routes.index);
app.get('/notifications', _notifications.notifications);
app.get('/python', pythonProxy);

function xxxxxxx(socket, redisClient, redisKey, redis_err, redis_reply) {

  console.log('redisClient.get() - redis_err: "' + redis_err
      + '" - redis_reply: "' + redis_reply + '"');

  if (redis_err !== null) {
    socket.emit('internal', {
      type : 'error',
      code : 'USER_ID_RETRIEVAL_RETURNED_ERROR',
      message : 'Error detected when trying to get user id.'
    });
    return;
  }

  if (redis_reply === null) {
    socket.emit('internal', {
      type : 'error',
      code : 'USERID_IS_NULL',
      message : 'Couldn\'t get userId.'
    });
    return;
  }

  // FIXME: should use something like 'get-and-delete'
  console.log("Remoging retrieved key");
  redisClient.del(redisKey);

  var userId = redis_reply;

  redisClient.on("error", function(err) {
    // TODO: infor this error to client (using websocket)
    // TODO: close this websocket (so the client knows and reconnect)
    console.log("Error " + err);
  });

  redisClient.on('message', function(pattern, data) {
    console.log('Suscriber received a message: ' + data);
    socket.emit('notification', {
      message : data
    });
  });

  var url = '/app/user/' + userId + '/notifications';
  console.log("Subscribing to " + url);
  redisClient.subscribe(url);

  socket.emit('internal', {
    type : 'success',
    code : 'SUBSCRIPTION_OK',
    message : 'Subscription to pub/sub ok.'
  });

}

io.of('/io/user/notifications').on('connection', function(socket) {
  console.log('Connection from ' + socket);

  socket.on('subscribe-to-notifications', function(data) {
    console.log('subscribe-to-notifications - data.uuid: "' + data.uuid);

    var redisKey = 'cookie-' + data.uuid;
    var redisClient = _redis.createClient();
    redisClient.get(redisKey, function(err, reply) {
      xxxxxxx(socket, redisClient, redisKey, err, reply);
    });
  });

});

server.listen(app.get('port'), function() {
  console.log('Express server listening on port ' + app.get('port'));
});

@@ -925,24 +925,76 @@
 yServer();%0A%0A
+// Function to proxy requests to Python http server%0A
 function pyt
@@ -1354,17 +1354,17 @@
 ;%0A%7D%0A%0A// 
-m
+M
 ap urls%0A
@@ -1487,24 +1487,151 @@
 );%0A%0A
-function xxxxxxx
+//%0A// Subscribe to the Redis to receive notifications, and re-send it to the client%0A// using Socket.IO%0A//%0Afunction subscribeUserToNotifications
 (soc
@@ -1668,16 +1668,20 @@
 dis_err,
+%0A   
  redis_r
@@ -1802,16 +1802,59 @@
  '%22');%0A%0A
+  // Check if response from Redis is valid%0A
   if (re
@@ -2060,16 +2060,59 @@
 n;%0A  %7D%0A%0A
+  // Check if response from Redis is valid%0A
   if (re
@@ -2335,16 +2335,123 @@
 -delete'
+ if exists%0A  // FIXME: is this realy neccesary? The key expires quickly, so,%0A  // maybe this isn't required
 %0A  conso
@@ -2462,17 +2462,17 @@
 og(%22Remo
-g
+v
 ing retr
@@ -2480,16 +2480,27 @@
 eved key
+ from Redis
 %22);%0A  re
@@ -2554,16 +2554,51 @@
 reply;%0A%0A
+  //%0A  // Hanlde Redis errors%0A  //%0A
   redisC
@@ -2799,16 +2799,67 @@
 %0A  %7D);%0A%0A
+  //%0A  // Handle messages received from Redis%0A  //%0A
   redisC
@@ -2961,16 +2961,71 @@
 + data);
+%0A%0A    // Re-send message to the browser using Socket.IO
 %0A    soc
@@ -3083,24 +3083,86 @@
  %7D);%0A  %7D);%0A%0A
+  //%0A  // Subscribe to URL of notifications for the user%0A  //%0A
   var url = 
@@ -3270,24 +3270,69 @@
 ribe(url);%0A%0A
+  // Inform client the subscription was done%0A
   socket.emi
@@ -3453,16 +3453,71 @@
 %7D);%0A%0A%7D%0A%0A
+//%0A// Attache '/io/user/notifications' to SocketIO%0A//%0A%0A
 io.of('/
@@ -3905,15 +3905,36 @@
     
-xxxxxxx
+subscribeUserToNotifications
 (soc

Add comments to code