// Setup: 
// npm install express
// npm install engine.io
// npm install eureca.io

// Pull in express
var express = require('express');

// Our app and server objects
var app = express(app);
var server = require('http').createServer(app);

// serve static files from the current directory
app.use(express.static(__dirname));

// get a eureca server
var EurecaServer = require('eureca.io').EurecaServer;

//create an instance of EurecaServer
var eurecaServer = new EurecaServer({
	// Allow out communication functions
	allow: ['handshake', 'spawnPlayer', 'kill', 'updateState']
});

// attach eurica to our server
eurecaServer.attach(server);

// Our list of clients
var clients = {};

// When a client connects
eurecaServer.onConnect(function(conn) {

	console.log('Connection %s from ', conn.id, conn.remoteAddress);

	// Grab the client proxy to call functions easily
	var remote = eurecaServer.getClient(conn.id);

	// Handshake with the client sending it it's new ID
	remote.handshake(conn.id);

	// Inform the client of all other players to spawn
	for (var c in clients) {
		var x = clients[c].state ? clients[c].state.x : 0;
		var y = clients[c].state ? clients[c].state.y : 0;

		remote.spawnPlayer(clients[c].id, x, y);
	}

	// Inform other clients to spawn this player
	for (var c in clients) {
		var x = remote.state ? remote.state.x : 0;
		var y = remote.state ? remote.state.y : 0;

		clients[c].remote.spawnPlayer(conn.id, x, y);
	}

	// Add the client to our list
	clients[conn.id] = {
		id: conn.id,
		remote: remote,
	}
});

// When a client disconnects
eurecaServer.onDisconnect(function(conn) {

	console.log('Disconnection ', conn.id);

	// delete this client
	delete clients[conn.id];

	// Notify other clients of disconnection
	for (var c in clients) {
		clients[c].remote.kill(conn.id);
	}
});

// When a client asks to update it's state
eurecaServer.exports.updateMe = function(state) {

	// Get conncection info
	var conn = this.connection;

	// Send new state to all other clients
	for (var c in clients) {
		clients[c].remote.updateState(conn.id, state);
	}

	// store the last known state
	clients[conn.id].state = state;
}

// Listen on port 80
server.listen(8000);