//
// rssi script
//
// var mySite = 'http://192.168.1.23' from myip.js
var url = mySite + '/state';
var rssiData = [];
var rssiIndex = 0;
var axes = {};
for (var i = 0; i<100; i++)
	rssiData[i] = 0;
setInterval(RefreshStatus, 250);

// -------------------------

getIt = function (aUrl, callback) {
	var xhr = new XMLHttpRequest();
	xhr.open('GET', aUrl, true);
	xhr.responseType = 'text';
	xhr.onload = function (e) {
		if (this.status === 200) {
			callback(this.response);
		}
	};
	xhr.send();
};

function RefreshStatus() {
	getIt(url,
		function(data) {
			obj = JSON.parse(data);
			UpdateGraph(obj.rssi);
			document.getElementById('rssi').innerHTML = 'RSSI: ' + obj.rssi;
			document.getElementById('uptime').innerHTML = 'Uptime: ' + obj.uptime;
		}
	);
}

function RSSIInit() {
	var canvas = document.getElementById('RSSIGraph');
	if (null === canvas || !canvas.getContext)
		return;
	ctx = canvas.getContext('2d');
	axes.w = 0.9 * canvas.width;
	axes.h = 0.8 * canvas.height;
	axes.x0 = 0.07 * canvas.width;	// x0 pixels from left to x=0
	axes.y0 = 0.10 * canvas.height;	// y0 pixels from top to y=0
	axes.scaleX = 100;	// # pixels from x=0 to x=1
	axes.scaleY = 100;
	axes.doNegativeX = false;
	ctx.clearRect(0, 0, canvas.width, canvas.height);
	ctx.rect(0, 0, canvas.width - 1, canvas.height - 1);
	ctx.strokeStyle = 'black';
	ctx.lineWidth = 1;
	ctx.stroke();
	showAxes(ctx, axes);
}

function UpdateGraph(rssi) {
	var xx, yy;
	rssi = -rssi;	// invert for convenience
	if (rssi > axes.scaleY)	// safety limit
		rssi = axes.scaleY;
	else if (rssi < 0)
		rssi = 0;
	rssiData[rssiIndex] = rssi;
	console.log('UpdateGraph(-' + rssi + ')');
	RSSIInit();
	x0 = axes.x0;
	y0 = axes.y0;
	ctx.beginPath();
	ctx.strokeStyle = 'rgb(250,128,128)';
	ctx.lineWidth = 5;
	for (var i = 0; i<100; i++) {
		pi = (rssiIndex + 1 + i) % 100;
		xx = x0 + i / axes.scaleX * axes.w;
		yy = y0 + rssiData[pi] / axes.scaleY * axes.h;
		ctx.lineTo(xx, yy);
	}
	ctx.stroke();
	ctx.beginPath();
	ctx.arc(xx, yy, 7, 0, 2 * Math.PI, false);
	ctx.fillstyle = 'green';
	ctx.fill();
	ctx.strokeStyle = '#003300';
	ctx.stroke();
	rssiIndex++;
	rssiIndex %= 100;
}

function showAxes(ctx, axes) {
	var x0 = axes.x0, w = axes.w;
	var y0 = axes.y0, h = axes.h;
	var xmin = axes.doNegativeX ? 0 : x0;
	ctx.lineWidth = 1;
	ctx.font = '12px Arial';
	ctx.textAlign = 'end';
	ctx.beginPath();
	ctx.strokeStyle = 'rgb(128,128,128)';
	ctx.moveTo(x0, y0);   ctx.lineTo(x0, y0 + h);  // Y axis
	for (var y = 0; y <= axes.scaleY; y += 10) {
		yy = axes.y0 + y / axes.scaleY * axes.h;
		ctx.moveTo(xmin, yy); ctx.lineTo(x0 + w, yy);  // X axis
		ctx.fillText(-y, x0 - 3, yy + 3);
	}
	ctx.font = '18px Arial';
	ctx.textAlign = 'start';
	ctx.fillText('RSSI Graph', axes.x0, axes.y0 - 6);
	ctx.stroke();
}
