var io;
var port = 13336;

var rooms = new Array();
var host = new Object();

initializeServer();

function initializeServer() {
    console.log('FGD Server running.');
    console.log('initializing socket.io...');
    io = require('socket.io').listen(port);
    console.log('OK, started listening on port ' + port);

}

io.sockets.on('connection', function(socket) {
    socket.set('nick', 'ukjent');

    socket.emit('setid', {id : socket.id});

    socket.on('createGame', function(data) {

        var r = Math.floor((Math.random()*1000000)+1);

        while(rooms.indexOf(r) >= 0)
            r = Math.floor((Math.random()*1000000)+1);

        rooms.push(r);
        host[r] = socket;        
        socket.join('r.' + r);

        socket.emit('createGame', {key : r});
    });

    socket.on('joinGame', function(data) {
        if(rooms.indexOf(parseInt(data.key)) >= 0 && io.sockets.clients('r.' + data.key).length < 8) {
            socket.join('r.' + data.key);
            socket.emit('joinGame', {res : true});
            socket.get('nick', function(data) {
                io.sockets.in('r.' + data.key).emit('add', { id : data});
            });

            for(sock in io.of('namespace').clients('room')) {
                sock.get('nick', function(data) {
                    socket.emit('add', sock.nick);
                });
            }
        } else {
            socket.emit('joinGame', {res : false});
        }
    });

    socket.on('leaveGame', function(data) {
        if(rooms.indexof(data.key) >= 0) {
            socket.leave('r.' + data.key);
            socket.emit('leaveGame', {res : true});
            socket.get('nick', function(data) {
                io.sockets.in('r.' + data.key).emit('remove', { id : socket.id});
            });
        } else {
            socket.emit('leaveGame', {res : false});
        } 
    });
    
    socket.on('disconnect', function() {
        socket.get('nick', function(data) {
           io.sockets.emit('remove', socket.id);
        });
    });

    socket.on('key', function(data) {
        host[parseInt(data.key)].emit('key', data);
    });

    socket.on('broadcast', function(data) {
        io.sockets.in('r.' + data.key).emit('broadcast', data);
    });

    socket.on('respawn', function(data) {
        io.sockets.in('r.' + data.key).emit('respawn', data); 
    });

    socket.on('dmg', function(data) {
        io.sockets.in('r.' + data.key).emit('dmg', data); 
    });

    socket.on('state', function(data) {
        io.sockets.in('r.' + data.key).emit('state', data); 
    });

    socket.on('spawn', function(data) {
        io.sockets.in('r.' + data.key).emit('spawn', data); 
    });

    socket.on('chestowner', function(data) {
        io.sockets.in('r.' + data.key).emit('chestowner', data); 
    });

    socket.on('setnick', function(data) {
        socket.set('nick', data.nick);
    })
});
