<!DOCTYPE html>
<html>
<head>
	<title>Sokery test</title>
</head>
<style type="text/css">
	body {
		padding: 0;
		margin: 0;
		font-family: "Courier New";
		font-size: 14px;
		background: #222;
		color: #c0c0c0;
	}
	input[type=text] {
		padding: 5px;
		background: #222;
		border: solid 1px #555;
		color: #eee;
	}
	button {
		background: #99cc00;
		border: none;
		font-size: 14px;
	}
	#panel {
		padding: 10px;
		position: fixed;
		top: 0;
		height: 50px;
		background: #333;
		width: 100%;
	}
	#output {
		margin-top: 70px;
	}
	.output {
		padding: 4px 10px;
	}
	.output:nth-child(odd) {
		background: #151515;
	}
</style>
<body>
	
<div id="panel">
	<div>Puerto</div>
	<input type="text" value="" id="port">
	<label>
		<input type="checkbox" id="echo" value="1">
		Eco a todo
	</label>

	<button type="button" id="listen">Listen</button>
</div>

<div id="output">
</div>

<script>
	var socket;
	var buttonListen;
	var fieldPort;
	var fieldEcho;
	var divOutput;

	function outputLine(text, color) {
		var div = document.createElement('div');
		div.className = 'output';
		div.innerHTML = text;
		if (color) {
			div.style.color = color;
		}
		divOutput.insertBefore(div, divOutput.childNodes[0]);
	}

	window.onload = function() {
		buttonListen = document.getElementById('listen');
		fieldPort = document.getElementById('port');
		divOutput = document.getElementById('output');
		fieldEcho = document.getElementById('echo');

		socket = new WebSocket('ws://' + location.host + '/live');

		socket.onmessage = function(message) {
			data = JSON.parse(message.data);
			

			if (data.op === 'recvd') {
				var host = data.from[0];
				var port = data.from[1];
				var originalPort = data.from[2];

				outputLine('['+host+':'+port+'/'+originalPort+'] ' + data.data);
			} else if (data.op === 'success') {
				outputLine(data.message, '#99ff99');
			} else if (data.op === 'error') {
				outputLine(data.message, '#ff9999');
			} else if (data.op === 'newclient') {
				var host = data.from[0];
				var port = data.from[1];
				var originalPort = data.from[2];
				outputLine('['+host+':'+port+'/'+originalPort+'] connected',
						   '#9999ff');
			} else if (data.op === 'connection_closed') {
				var host = data.from[0];
				var port = data.from[1];
				var originalPort = data.from[2];
				outputLine('['+host+':'+port+'/'+originalPort+'] connection closed',
						   '#ffee99');
			}
			console.log(data);
		}

		buttonListen.onclick = function() {
			if (socket) {
				socket.send(JSON.stringify({
					op: 'listen',
					port: parseInt(fieldPort.value),
					options: {
						echo_all: fieldEcho.checked
					}
				}))
			}
		};
	}
</script>

</body>
</html>