var SocketIO = require("socket.io");
var io;

/*
 *  Init
 * */
exports.init = function (link) {
    init();
};

/*
 *  Listen
 * */
exports.listen = function (link) {
    // TODO
    link.send(200, { op: "listen" });
};

/*
 *  Emit
 * */
exports.emit = function (link) {
    // TODO
    link.send(200, { op: "emit" });
};


/*
 *  init ()
 *  This function set the io variable
 *
 * */
function init () {
    // Socket.io server listens to our app
    io = SocketIO.listen(M.app.server);
}

/*
 *  emit (object, function)
 *  Emit some event and data
 *
 *  options:
 *   - event: the event name
 *   - data:  data that must be emited
 *
 *  callback:
 *   - callback function
 * */
function emit (options, callback) {

    // options must be an object
    options = options || {};

    // callback must be a function
    callback = callback || function () {};

    // init io, if it is not inited
    if (!io) { init(); }

    // emit that event and data
    io.sockets.emit(options.event, options.data);
}

/*
 *  listen (object, function)
 *  Listen on some event and callback the socket
 *
 *  options:
 *   - event: the event name that listen to
 *
 *  callback: the function that must be fired
 *            on that event
 *
 * */
function listen (options, callback) {

    // options must be an object
    options = options || {};

    // callback must be a function
    callback = callback || function () {};

    // init io, if it is not inited
    if (!io) { init(); }

    // listen on that event
    io.sockets.on(options.event, callback);
}

/*
 *  The events interface:
 *   - sockets.init
 *   - sockets.emit
 *   - sockets.listen
 * */
M.on("sockets.init", init);
M.on("sockets.emit", emit);
M.on("sockets.listen", listen);

@@ -165,53 +165,231 @@
 ) %7B%0A
+%0A
     // 
-TODO%0A    link.send(200, %7B op: %22listen%22
+call listen function%0A    listen(link.data.options, function (err, data) %7B%0A%0A        // handle error%0A        if (err) %7B return link.send(400, err); %7D%0A%0A        // send success response%0A        link.send(200, data);%0A   
  %7D);
@@ -448,51 +448,227 @@
 ) %7B%0A
+%0A
     // 
-TODO%0A    link.send(200, %7B op: %22emit%22
+call emit function%0A    emit(link.data.options, function (err, data) %7B%0A%0A        // handle error%0A        if (err) %7B return link.send(400, err); %7D%0A%0A        // send success response%0A        link.send(200, data);%0A   
  %7D);
@@ -1355,16 +1355,32 @@
 .data);%0A
+    callback();%0A
 %7D%0A%0A/*%0A *

Call emit/listen functions from the operation.