module.exports = function() {

    var module={};

    module.connection = function(socket) {

        var sys = require('sys');
        var exec = require('child_process').exec;

        console.log("new client");

        function emit(signal, data, info) {
            if (typeof data == 'string') {
                console.log("<- signal: "+signal+"("+data+")");
            } else {
                console.log("<- signal: "+signal);
            }
            if (info) console.log(info);
            socket.emit(signal, data);
        }

        function broadcast(signal, data) {
            console.log("<= signal: "+signal);
            socket.broadcast.emit(signal, data);
        }

        function containerinspect(error, stdout, stderr) {
            console.log(error);
            if (!error && !stderr) {
                var res = {};
                JSON.parse(stdout).forEach(function(c) {
                    res[c.Id] = c;
                });
                emit("containers", res);
            }
        }
        
        function containerlist(error, stdout, stderr) {
            console.log(error);
            console.log("docker inspect "+stdout.trim().replace(/\n/g, " "));
            if (!error && !stderr)
                exec("docker inspect "+stdout.trim().replace(/\n/g, " "),
                     containerinspect);
        }

        socket.on("containers", function() {
            console.log("-> containers");
            exec("docker ps -aq",
                 containerlist);
        });
        
    }
    
    return module;
}
