{{template "header.html" dict "isMobile" false "title" "Информация с датчиков Центра Обработки Данных"}}

<header>
	<a href="/"><img id='logo' src='/public/img/nrnu_mephi.png'></a>
	<table style='display:inline-table;margin-left:20px'>
		<tr>
			<td>
				<a href="https://mephi.ru/">НИЯУ МИФИ</a> / <a href="https://it.mephi.ru">УИ</a> / <a href="/">{{ .title }}</a>
			</td>
		</tr>
		<tr>
			<td style='line-height:10px'>
				<span style='font-size:10px;color:#888'>Контакты для связи: <a href='mailto:embed@ut.mephi.ru'>embed@ut.mephi.ru</a></span>
			</td>
		</tr>
	</table>
	<div id='logout' style='float:right;padding-right:10px'>| <a href='/logout' style='border-bottom: 1px #444 dotted'>Выйти</a></div>
	<div id='ts' style='float:right;padding-right:10px'></div>
</header>
<main>

<table id='dashboardLayout' width='100%'>
	<tr>
		<td id='mapContainer' width='547px'>
			{{template "Dashboard/_2DMap.html" .}}
		</td>
		<td id='sensors'>
			<ul style='margin: 10px'>
			</ul>
			<span style='visibility:hidden'>hello there! 0xE40C8E30679C</span>
		</td>
		<td id='graphs' width='99%'>
			<span id='chartConfig'>
				&nbsp;Интервал агрегации:
				<input id='aggregationType1' type='radio' name='aggregationType' value=1        ><label for="aggregationType1"> секунда </label>
				<input id='aggregationType2' type='radio' name='aggregationType' value=2 checked><label for="aggregationType2"> минута </label>
				<input id='aggregationType3' type='radio' name='aggregationType' value=3        ><label for="aggregationType3"> 5 минут </label>
				<input id='aggregationType4' type='radio' name='aggregationType' value=4        ><label for="aggregationType4"> час </label>
				<input id='aggregationType5' type='radio' name='aggregationType' value=5        ><label for="aggregationType5"> сутки </label>
				<input id='aggregationType6' type='radio' name='aggregationType' value=6        ><label for="aggregationType6"> неделя </label>
				|
				Глубина истории: <input id='limit' type='number' name='limit' value='2500' min=2 max=655350>
			</span>
			<div id='chartDiv'>
			</div>
		</td>
		<td>
		</td>
	</tr>
</table>

{{template "Dashboard/_mobileDashboardLayout.html" dict "isMobile" false "sensors" .sensors "mobileAutoupdate" .mobileAutoupdate "mobileShowNames" .mobileShowNames}}

<script>
	var sensors = {
	{{ range $sensorId,$sensorInfo := .sensors }}
		{{ $sensorId }}: {{$sensorInfo}},
	{{ end }}
		0:{}
	};
	var groups  = {{.groups}};

	var is_debug  = {{ .DevMode }}
	var is_mobile = window.matchMedia("all and (max-width: 800px)").matches;

	var currentSensorId = 0;

	var chart = AmCharts.makeChart("chartDiv", {
			"type": "serial",
			"theme": "light",
			"marginTop":0,
			"marginRight": is_mobile?0:80,
			"zoomOutText": "Показать всё",
			/*"zoomOutOnDataUpdate": false,*/
			/*"zoomControl": {
				"zoomControlEnabled": true,
			},*/
			"valueAxes": [{
				"title": is_mobile?null:"T",
				"axisAlpha": 0,
				"position": "left",
				"minimum": 10,
				"maximum": 40,
			}],
			"dataProvider": [{
				"Date":Date.now(),
				"ConvertedValue": 0.0,
				"ConvertedValue2":0.0,
				"ConvertedValue3":0.0,
			}],
			"graphs": [
			{
				"id":"g1",
				"balloonText": "[[Date]]<br><b><span style='font-size:14px;'>[[ConvertedValue]]</span></b>",
				"lineColor": "#d1655d",
				"lineThickness": 2,
				"negativeLineColor": "#637bb6",
				"type": "line",
				"valueField": "ConvertedValue",
				"negativeBase": 23.5,
			},
			{
				"id":"g2",
				"balloonText": "[[Date]]<br><b><span style='font-size:14px;'>[[ConvertedValue2]]</span></b>",
				"lineColor": "#61d55d",
				"lineThickness": 2,
				"negativeLineColor": "#630080",
				"type": "line",
				"valueField": "ConvertedValue2",
				"negativeBase": 23.5,
			},
			{
				"id":"g3",
				"balloonText": "[[Date]]<br><b><span style='font-size:14px;'>[[ConvertedValue3]]</span></b>",
				"lineColor": "#d1655d",
				"lineThickness": 2,
				"negativeLineColor": "#636060",
				"type": "line",
				"valueField": "ConvertedValue3",
				"negativeBase": 23.5,
			},
			],
			"chartScrollbar": is_mobile?null:{
				"graph":"g1",
				"gridAlpha":0,
				"color":"#888888",
				"scrollbarHeight":55,
				"backgroundAlpha":0,
				"selectedBackgroundAlpha":0.1,
				"selectedBackgroundColor":"#888888",
				"graphFillAlpha":0,
				"autoGridCount":true,
				"selectedGraphFillAlpha":0,
				"graphLineAlpha":0.2,
				"graphLineColor":"#c2c2c2",
				"selectedGraphLineColor":"#888888",
				"selectedGraphLineAlpha":1

			},
			"chartCursor": {
				"categoryBalloonDateFormat": "YYYY-MM-DD HH:NN:SS",
				"cursorPosition": "mouse",
			},
			"dataDateFormat": "YYYY-MM-DD HH:NN:SS",
			"categoryField": "Date",
			"categoryAxis": {
				"minPeriod": "ss",
				"parseDates": true,
				"minorGridAlpha": 0.1,
				"minorGridEnabled": true
			},
			"export": {
				"enabled": true,
				"dateFormat": "YYYY-MM-DD HH:NN:SS"
			}
		});

	function updateTimestamp() {
		$.ajax({
			cache:		false,
			dataType:	'json',
			url:		'/TS.json',
			success:	function(data){
				$('#ts').html(data.ts);
			},
		});
	}
	function updateMap() {
		$.ajax({
			cache:		false,
			dataType:	'html',
			url:		'/Map/MainDC.html',
			success:	function(data){
				$('#main-dc').html(data);
			},
		});
		$.ajax({
			cache:		false,
			dataType:	'html',
			url:		'/Map/ReserveDC.html',
			success:	function(data){
				$('#reserve-dc').html(data);
			},
		});
	}

	function updateSensorsInfo() {
		$.ajax({
			cache:		false,
			dataType:	'json',
			url:		'/Status.json',
			success:	function(data){
				groups  = data.groups;
				sensors = data.sensors;
				updateSensorsList();
			},
		});
	}

	if (is_mobile) {
		$('#limit').val('60');
		//$('#aggregationType1').prop('checked', true);
	}

	$('#chartConfig input').change(function(){
		selectSensor(currentSensorId);
	})

	var selectedItem = window.location.href.split('#')[1];

	if (typeof(selectedItem) != 'undefined' && selectedItem != null && selectedItem != "") {
		selectedVars = selectedItem.split('=');
		switch (selectedVars[0]) {
			case 'selectSensor':
				selectSensor(selectedVars[1]);
				break;
			case 'selectSensorsGroup':
				selectSensorsGroup(selectedVars[1]);
				break;
		}
	} else {
		selectSensor(0);
	}

	if (is_mobile) {
		setInterval(function() {
			updateMobileStatus();
		}, 5000);
		mobileRender();
	}

	if (!is_mobile && !is_debug) {
		setInterval(function() {
			updateTimestamp();
		}, 1000);

		setInterval(function() {
			updateMap();
		}, 5000);

		setInterval(function() {
			updateSensorsInfo();
		}, 5000);
	}

	var currentSensorsGroup = null;

	function updateSensorsList() {
		var container = $('#sensors ul');

		container.html('');

		if (currentSensorsGroup == null) {
			return;
		}

		for (var i = 0; i < currentSensorsGroup.SensorIds.length; i++) {
			var sensorId = currentSensorsGroup.SensorIds[i];
			var sensor   = sensors[sensorId];
			if (sensor == null) {
				continue;
			}
			container.append("<li><a href='#' onclick='selectSensor("+sensorId+")'>"+sensor.Name+" ("+sensor.Value+")</a></li>");
		}
	}

	function selectSensorsGroup(groupName) {
		window.location='/#selectSensorsGroup='+groupName;

		currentSensorsGroup = groups[groupName];

		updateSensorsList();

		selectSensor(currentSensorsGroup.DefaultSensorId);
	}

	var chartPrevRequest = null
	var updateChartTimeout = null;

	function selectSensor(sensorId, isUpdateOnly) {
		if (chartPrevRequest != null) {
			chartPrevRequest.abort();
			chartPrevRequest = null;
		}

		if (updateChartTimeout != null) {
			clearTimeout(updateChartTimeout);
			updateChartTimeout = null;
		}

		if (sensorId == 0) {
			window.location='#';
		} else {
			window.location='/#selectSensor='+sensorId;
		}

		var aggregationType = parseInt($('input[name=aggregationType]:checked').val());

		currentSensorId = sensorId;
		chartPrevRequest = $.ajax({
			cache:		false,
			dataType:	'json',
			url:		'/HistoryRecords.json?order=date:DESC&limit='+$('#limit').val()+'&historyRecord.AggregationType='+aggregationType+'&historyRecord.SensorId='+sensorId,
			success:	function(data){
				if (currentSensorId != sensorId) {
					if (is_debug) {
						console.log("currentSensorId != sensorId", currentSensorId, sensorId);
					}
					return;
				}
				chartPrevRequest = null;
				if (sensorId == 0) {
					var mergedHistory = {};
					for (var i = 0; i < data.historyRecords1.length; i++) {
						mergedHistory[data.historyRecords1[i].Date] = {}
						mergedHistory[data.historyRecords1[i].Date].ConvertedValue  = data.historyRecords1[i].ConvertedValue
					}
					for (var i = 0; i < data.historyRecords2.length; i++) {
						if (typeof(mergedHistory[data.historyRecords2[i].Date]) == 'undefined') {
							mergedHistory[data.historyRecords2[i].Date] = {}
						}
						mergedHistory[data.historyRecords2[i].Date].ConvertedValue2 = data.historyRecords2[i].ConvertedValue
					}
					for (var i = 0; i < data.historyRecords3.length; i++) {
						if (typeof(mergedHistory[data.historyRecords3[i].Date]) == 'undefined') {
							mergedHistory[data.historyRecords3[i].Date] = {}
						}
						mergedHistory[data.historyRecords3[i].Date].ConvertedValue3 = data.historyRecords3[i].ConvertedValue
					}

					data.historyRecords = []
					for (var key in mergedHistory) {
						data.historyRecords.push({
							Date: key,
							ConvertedValue:  mergedHistory[key].ConvertedValue,
							ConvertedValue2: mergedHistory[key].ConvertedValue2,
							ConvertedValue3: mergedHistory[key].ConvertedValue3,
						});
					}
				}
				data.historyRecords.sort(function(a, b){return a.Date < b.Date ? -1 : a.Date > b.Date})
				chart.dataProvider = data.historyRecords;
				chart.validateData();
				if (!isUpdateOnly) {
					chart.zoomOut();
				}
				//try{chart.zoomToIndexes(Math.round(chart.dataProvider.length * 0.5), chart.dataProvider.length)}catch(e){}
			},
		});

		var updateIntervalSecs = 60;

		switch (aggregationType) {
			case 1:
				updateIntervalSecs=2;
				break;
			case 2:
				updateIntervalSecs=60;
				break;
			case 3:
				updateIntervalSecs=60*5;
				break;
			case 4:
				updateIntervalSecs=60*60;
				break;
			case 5:
				updateIntervalSecs=60*60*24;
				break;
			case 6:
				updateIntervalSecs=60*60*24*7;
				break;
		}

		updateChartTimeout = setTimeout(function() {
			selectSensor(sensorId, true);
		}, 1000 * updateIntervalSecs);
	}
</script>

</main>
<div class="container">
	<div class="row">
		<div class="span6">
			{{template "flash.html" .}}
		</div>
	</div>
</div>

{{template "footer.html" .}}
