<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ESP node</title>
<style>
html { font-family:sans-serif }
table { border-collapse:collapse; }
td,th { padding: 4px 10px; min-width: 65px; }
td { min-width: 70px; }

th { text-align:left; }
tbody th { text-align:center; }
tbody th {border-right: 1px solid black;}
thead th { text-align:center;padding-top:0; }
td { text-align:right; }
td[c],[c] td { text-align:center; }
td[l],[l] td { text-align:left; }
td[r],[r] td { text-align:right; }
td[ed] {cursor:pointer;}
td[ed]:hover {text-decoration:underline;}
table[thl] tbody th {text-align:left;}
figure {
	border-top:3px solid black;
	border-bottom:3px solid black;
	display: inline-block;
	padding: 5px 0;
	margin: 0 0 15px 15px;
}
thead tr { border-bottom: 2px solid black; }
</style>
</head>
<body>
<h1>ESP node {version}</h1>

<a href="/reboot">Restart node</a>

<script>
var kv_re = /^(-?[0-9.-]+)\s+(.+)$/;
var Qi = function (x) { return document.getElementById(x) };
var data = {};
function update(data) {
	if (data) {
		var rows = data.split('\x1e');
		rows.forEach(function (v) {
			var kv = v.split('\x1f');
			var el = Qi(kv[0]);
			if (!el) return;
			var suf = '';
			var res = kv_re.exec(el.textContent);
			if (res) suf = ' ' + res[2];
			el.textContent = kv[1] + suf;
			data[kv[0]] = kv[1];
		});
	} else {
		var xhr=new XMLHttpRequest();
		xhr.onreadystatechange = function () {
			if (xhr.readyState===4){
				if (xhr.status===200) {
					update(xhr.responseText);
				}
				setTimeout(update, 1000);
			}
		};
		xhr.onerror = function () {
			setTimeout(update, 1000);
		};
		xhr.open('GET', '/data');
		xhr.send();
	}
}

function mkXhr() {
	var xhr=new XMLHttpRequest();
	xhr.onreadystatechange = function () {
		if (xhr.readyState===4 && xhr.status!==200) {
			alert(xhr.responseText || xhr.statusText || 'Request failed');
		}
	};
	return xhr;
}

function editOpt() {
	var k = this.id;
	var v = prompt(k+' =', data[k]||'');
	if (v !== null) {
		var xhr = mkXhr();
		xhr.open('POST', '/set');
		xhr.send("key="+k+'&value='+encodeURIComponent(v));
	}
}

function toggleOpt() {
	var xhr = mkXhr();
	xhr.open('POST', '/toggle');
	xhr.send("x="+this.id);
}

/*
setTimeout(update, 500);
for(var i=1;i<8;i++) {
	if(i<7) Qi('i'+i+'_max').addEventListener('click', editOpt);
	Qi('ch'+i+'_state').addEventListener('click', toggleOpt);
}
*/
</script>