"use strict";

var http = require('http');
var url = require('url');

var WebsocketServer = require('websocket').server;

var server = http.createServer(function(request,response) {

	function getPostParams(request, callback) {
	    var qs = require('querystring');

	    if (request.method == 'POST') {
	        var body = '';

	        request.on('data', function (data) {
	            body += data;

	            if (body.length > 1e6)
	                request.connection.destroy();
	        });

	        request.on('end', function () {
	            var POST = qs.parse(body);
	            callback(POST);
	        });
	    }
	}

    if (request.method === "POST") {
    	getPostParams(request, function(POST) {	
			messageClients(POST.data);
			response.writeHead(200);
			response.end();
		});
		return;
	}
});
server.listen(8080);


var websocketServer = new WebsocketServer({
	httpServer: server
});

websocketServer.on("request", websocketRequest);


// websockets storage
global.clients = {};
var connectionId = 0;
function websocketRequest(request) {

	var connection = request.accept(null, request.origin); 

	connectionId++;
	clients[connectionId] = connection;

}

function messageClients(message) {

	for (var i in clients) {
		clients[i].sendUTF(message);
	}

}
