$('#deleteDevice').on('click', function(e) {
	e.preventDefault();
	var uuid = $(this).data('uuid');
	var csrf = $(this).data('csrftoken');
	bootbox.confirm({
	    message: "Are you sure you want to delete the device " + uuid + "?",
	    buttons: {
	        confirm: {
	            label: 'Yes',
	            className: 'btn-success'
	        },
	        cancel: {
	            label: 'No',
	            className: 'btn-danger'
	        }
	    },
	    callback: function (result) {
	        if(result) {
				// TODO Permissions do not allow ordinay users to delete their own
				//      devices using the generic call. 
				
				/* 
	        	var url = '/app/api/objects/networkDevices/' + uuid;
	    		$.ajax({
	                url: url,
					beforeSend: function(request) {
						request.setRequestHeader("CsrfToken", csrf);
					},
	                type: 'delete',
	                dataType: 'json',
	                success: function (data) {
						window.location.href = '/';
	                }
	            })
				*/
				
				var url = '/vpn-deauthorize?uuid=' + uuid;
	    		$.ajax({
	                url: url,
					beforeSend: function(request) {
						request.setRequestHeader("CsrfToken", csrf);
					},
	                type: 'get',
	                success: function (data) {
						window.location.href = '/app/ui/vpn-devices';
	                }
	            })
				;
	        }
	    }
	});
});

am5.addLicense('AM5C387765625');
am5.ready(function() {


	// Create root element
	// https://www.amcharts.com/docs/v5/getting-started/#Root_element
	var root = am5.Root.new("chartdiv");
	var txMax = parseInt($('body').data('tx-max'));
	var rxMax = parseInt($('body').data('rx-max'));
	var max = Math.max(txMax, rxMax) / 1000 / 1000;


	// Set themes
	// https://www.amcharts.com/docs/v5/concepts/themes/
	try {
		root.setThemes([
			am5themes_Dark.new(root)
		]);
	}
	catch(e) {
		root.setThemes([
			am5themes_Animated.new(root)
		]);
	}


	// Generate random data
	var value = 100;

	function generateChartData() {
		var chartData = [];
		var firstDate = new Date();
		firstDate.setDate(firstDate.getDate() - 1000);
		firstDate.setHours(0, 0, 0, 0);

		for (var i = 0; i < 50; i++) {
			var newDate = new Date(firstDate);
			newDate.setSeconds(newDate.getSeconds() + i);

			//value += (Math.random() < 0.5 ? 1 : -1) * Math.random() * 10;

			chartData.push({
				date: newDate.getTime(),
				value: 0 /*value*/
			});
		}
		return chartData;
	}

	var rxData = generateChartData();
	var txData = generateChartData();


	// Create chart
	// https://www.amcharts.com/docs/v5/charts/xy-chart/
	var chart = root.container.children.push(am5xy.XYChart.new(root, {
		focusable: true,
		panX: true,
		panY: true,
		wheelX: "panX",
		wheelY: "zoomX",
		pinchZoomX: true,
		paddingLeft: 0
	}));
	chart.getNumberFormatter().set("numberFormat", "#'MB/s'");
	chart.get("colors").set("colors", [
	  am5.color(0xE95420),
	  am5.color(0x38B44A)
	]);
	$('#rxTitle').attr('style','color: #E95420');
	$('#txTitle').attr('style','color: #38B44A');

	var easing = am5.ease.linear;


	// Create axes
	// https://www.amcharts.com/docs/v5/charts/xy-chart/axes/
	var xAxis = chart.xAxes.push(am5xy.DateAxis.new(root, {
		maxDeviation: 0.5,
		groupData: false,
		extraMax: 0.1, // this adds some space in front
		extraMin: -0.1,  // this removes some space form th beginning so that the line would not be cut off
		baseInterval: {
			timeUnit: "second",
			count: 1
		},
		renderer: am5xy.AxisRendererX.new(root, {
			minorGridEnabled: true,
			minGridDistance: 50
		}),
		tooltip: am5.Tooltip.new(root, {})
	}));

	var yAxis = chart.yAxes.push(am5xy.ValueAxis.new(root, {
		min: 0,
		max: max,
		renderer: am5xy.AxisRendererY.new(root, {})
	}));


	// Add series
	// https://www.amcharts.com/docs/v5/charts/xy-chart/series/
	var rxSeries = chart.series.push(am5xy.LineSeries.new(root, {
		name: "Inbound",
		xAxis: xAxis,
		yAxis: yAxis,
		valueYField: "value",
		valueXField: "date",
		tooltip: am5.Tooltip.new(root, {
			pointerOrientation: "horizontal",
			labelText: "{valueY}"
		})
	}));
	
	var txSeries = chart.series.push(am5xy.LineSeries.new(root, {
		name: "Outbound",
		xAxis: xAxis,
		yAxis: yAxis,
		valueYField: "value",
		valueXField: "date",
		tooltip: am5.Tooltip.new(root, {
			pointerOrientation: "horizontal",
			labelText: "{valueY}"
		})
	}));

	// tell that the last data item must create bullet
	rxData[rxData.length - 1].bullet = true;
	txData[txData.length - 1].bullet = true;
	rxSeries.data.setAll(rxData);
	txSeries.data.setAll(txData);
	
	var animateBullets = function(root, series, dataItem) {
		// only create sprite if bullet == true in data context
		if (dataItem.dataContext.bullet) {
			var container = am5.Container.new(root, {});
			var circle0 = container.children.push(am5.Circle.new(root, {
				radius: 5,
				fill: am5.color(series == rxSeries ? 0xff0000 : 0x00ff00)
			}));
			var circle1 = container.children.push(am5.Circle.new(root, {
				radius: 5,
				fill: am5.color(series == rxSeries ? 0xff0000 : 0x00ff00)
			}));
	
			circle1.animate({
				key: "radius",
				to: 20,
				duration: 1000,
				easing: am5.ease.out(am5.ease.cubic),
				loops: Infinity
			});
			circle1.animate({
				key: "opacity",
				to: 0,
				from: 1,
				duration: 1000,
				easing: am5.ease.out(am5.ease.cubic),
				loops: Infinity
			});
	
			return am5.Bullet.new(root, {
				locationX: undefined,
				sprite: container
			})
		}
	}



	// Create animating bullet by adding two circles in a bullet container and
	// animating radius and opacity of one of them.
	rxSeries.bullets.push(animateBullets)
	txSeries.bullets.push(animateBullets)


	// Add cursor
	// https://www.amcharts.com/docs/v5/charts/xy-chart/cursor/
	var cursor = chart.set("cursor", am5xy.XYCursor.new(root, {
		xAxis: xAxis
	}));
	cursor.lineY.set("visible", false);


	// Update data every second
	setInterval(function() {
		//var value = Math.random() * maxValue;
		
		am5.net.load("/vpn-graph/peer-throughput?pubkey=" + encodeURIComponent( $('body').data('pubkey'))).then(function(result) {
			var stats = am5.JSONParser.parse(result.response);
			if(!stats) {
				window.location.href = '/';
			}
			else {
				$('#rx').html(humanFileSize(stats.rx, true));
				$('#tx').html(humanFileSize(stats.tx, true));
				$('#rxSpeed').html(humanFileSize(stats.rxBps, true) + '/s');
				$('#txSpeed').html(humanFileSize(stats.txBps, true) + '/s');
				addData(stats.rxBps / 1000 / 1000, rxSeries);
				addData(stats.txBps / 1000 / 1000, txSeries);
			}
		}).catch(function(result) {
			console.log("Error loading " + result.xhr.responseURL);
		});
		
	}, 1000);


	function addData(newValue, series) {
		var lastDataItem = series.dataItems[series.dataItems.length - 1];

		var lastValue = lastDataItem.get("valueY");
		var lastDate = new Date(lastDataItem.get("valueX"));
		var time = am5.time.add(new Date(lastDate), "second", 1).getTime();
		series.data.removeIndex(0);
		series.data.push({
			date: time,
			value: newValue
		})

		var newDataItem = series.dataItems[series.dataItems.length - 1];
		newDataItem.animate({
			key: "valueYWorking",
			to: newValue,
			from: lastValue,
			duration: 600,
			easing: easing
		});

		// use the bullet of last data item so that a new sprite is not created
		newDataItem.bullets = [];
		newDataItem.bullets[0] = lastDataItem.bullets[0];
		newDataItem.bullets[0].get("sprite").dataItem = newDataItem;
		// reset bullets
		lastDataItem.dataContext.bullet = false;
		lastDataItem.bullets = [];


		var animation = newDataItem.animate({
			key: "locationX",
			to: 0.5,
			from: -0.5,
			duration: 600
		});
		if (animation) {
			var tooltip = xAxis.get("tooltip");
			if (tooltip && !tooltip.isHidden()) {
				animation.events.on("stopped", function() {
					xAxis.updateTooltip();
				})
			}
		}
	}


	// Make stuff animate on load
	// https://www.amcharts.com/docs/v5/concepts/animations/
	chart.appear(1000, 100);

}); // end am5.ready()