var http = require('http');
var WSServer = require('websocket').server;

var url = require('url');
var clientHtml = require('fs').readFileSync('client.html');

var plainHttpServer = http.createServer(function(req, res) {
	res.writeHead(200, { 'Content-Type': 'text/html'});
	res.end(clientHtml);
}).listen(8080);

var webSocketServer = new WSServer({httpServer: plainHttpServer});
var accept = ['localhost', '127.0.0.1'];

webSocketServer.on('request', function (req) {
	  req.origin = req.origin || '*';
    console.log('origin: ' + req.origin);
	  if (accept.indexOf(req.origin) === -1) {
		    req.reject();
		    console.log(req.origin + ' access not allowed.');
		    return;
	  }

	  var websocket = req.accept(null, req.origin);

	  websocket.on('message', function(message) {
		  //console.log('"' + message.utf8Data + '" is recieved from ' + req.origin + '!');
		  //if (message.utf8Data === 'Hello') {
			// websocket.send('sended from WebSocket Server');
		  //}

        if (message.utf8Data != undefined) {
            // console.log('Received Message: ' + message.utf8Data);
            console.log('Received Message: ' + message.utf8Data.length);
            websocket.sendUTF(message.utf8Data);
        }
        else {
            console.log('Received Binary Message: ' + message.binaryData.length);
            /*
              var s = '';
              for (var i = 0; i < message.binaryData.length; i++) {
              if (i > 0) s += ', ';
              s += message.binaryData[i];
              }
              console.log(s);
            */
            websocket.sendBytes(message.binaryData);
        }
	});

	websocket.on('close', function (code,desc) {
		console.log('connection released! :' + code + ' - ' + desc);
	});
});
