var destroy = [];

function loadChart() {
	var charts = document.getElementsByTagName('chart');
	for (var i = 0; i < charts.length; i++) {
		var chart = charts[i];
		destroy.push(getGraph(chart, chart.getAttribute('label'), chart.getAttribute('unit'), chart.getAttribute('attr'), Number(chart.getAttribute('min')), Number(chart.getAttribute('max')), chart.getAttribute('meter-source')));
	}
}

function destroyChart() {
	for (var i = 0; i < destroy.length; i++) {
		if (destroy[i] == null) continue;
		destroy[i]();
	}
	destroy = [];
}

function getGraph(ctx, title, unit, attribute, min, max, meterSource) {
	if (attribute == undefined) return null;
	var hours= Number(document.getElementById("hours").value);
	var meter= document.getElementById(meterSource).value;
	if (meter == 0) return;

	var labels = [];
	var p = [null, [], [], []];
	var n = [];

	var chart = Highcharts.chart(ctx, {
		colors: ['#C55', '#5C5', '#55C', '#555'],
		chart: {
			zoomType: 'x',
			animation: false,
		},
		title: {
			text: title
		},
		xAxis: {
			type: 'datetime'
		},
		yAxis: {
			softMin: min,
			softMax: max,
			title: {
				text: unit
			}
		},
		legend: {
			enabled: true
		},
		tooltip: {
			shared: true
		},
		plotOptions: {
			series: {
				marker: {
					radius: 0
				},
				lineWidth: 2,
				states: {
					hover: {
						lineWidth:2
					}
				},
				animation: false
			}
		}
	});
	var init = false;
	var start = new Date(Date.now()-1000*60*60*hours)
	var timeout;
	var updateGraphData = function() {
		fetch('https://5groningen02.housing.rug.nl/api/pq/'+meter+'/'+attribute+'/'+start.toISOString())
			.then(function (response) {
				if (response.status != 200) return new Promise((resolve) => { resolve([]); });
				return response.json()
			})
			.then(function (data) {
				if (data == null) {
					if (hours <= 24) timeout = setTimeout(updateGraphData, 1000);
					return
				}

				if (!init) {
					init = true

					chart.addSeries({type: 'line', name: 'Phase 1', data: []});
					chart.addSeries({type: 'line', name: 'Phase 2', data: []});
					chart.addSeries({type: 'line', name: 'Phase 3', data: []});

					if (data[0].null != null) chart.addSeries({type: 'line', name: 'Null', data: [], visible: false});
				}

				data.reverse();
				data.forEach(function(item) {
					var t = formatTime(item.time);
					if ((p[1].length > 0) && (p[1][0][0] < t-(hours*60*60*1000))) {
						p[1].shift(); p[2].shift(); p[3].shift(); n.shift();
					}

					p[1].push([t, item.phase_1]);
					p[2].push([t, item.phase_2]);
					p[3].push([t, item.phase_3]);

					if (item.null != null) n.push([t, item.null]);

					start = new Date(new Date(item.time).getTime()+1000);
				});
				chart.series[0].setData(p[1]);
				chart.series[1].setData(p[2]);
				chart.series[2].setData(p[3]);
				if (chart.series.length == 4) chart.series[3].setData(n);

				chart.update({}, true);

				if (hours <= 24) timeout = setTimeout(updateGraphData, 1000);
			})
	}

	updateGraphData();

	return function() {
		clearTimeout(timeout);
		chart.destroy();
	}
}

function formatTime(t) {
	var d = new Date(t)
	return d-0+2*60*60*1000
}

Number.prototype.pad = function(size) {
	var s = String(this);
	while (s.length < (size || 2)) {s = "0" + s;}
	return s;
}