angular.module("robware").controller('temperature', ["$scope", "temperatureService", "$interval", function($scope, temperatureService, $interval) {
	$scope.readings = [];
	$scope.temperatureData = {};

	$scope.$watch("readings", function() {
		for (var i = 0; i < $scope.readings.length; i++) {
			$scope.readings[i].Timestamp = new Date($scope.readings[i].Timestamp * 1000);
		}
	});

	function getData() {
		temperatureService.getReadings().then(function(data) {
			$scope.readings = data;
		});
	}
	$interval(getData, 60000);

	function updateCurrentTemperature() {
		temperatureService.getCurrentTemperatureData().then(function(data) {
			$scope.temperatureData = data;
		});
	}
	$interval(updateCurrentTemperature, 5000);

	var graphAdjustment = 10;
	
	$scope.getGraphPercentage = function() {
		var graphTarget = ($scope.temperatureData.target * 1.2) - graphAdjustment;
		var graphTemperature = $scope.temperatureData.temperature - graphAdjustment;
		return Math.min((graphTemperature / graphTarget) * 100, 100);
	};

	function getPercentage() {
		return (($scope.temperatureData.target - graphAdjustment) / (($scope.temperatureData.temperature * 1.5) - graphAdjustment)) * 100;
	}

	$scope.getRed = function() {
		var percentage = getPercentage();
		return 255 * (1 - (Math.min(50, percentage) / 50));
	};

	$scope.getBlue = function() {
		var percentage = Math.max(getPercentage() - 50, 0);
		return 255 * (Math.min(50, percentage) / 50);
	};

	$scope.getGreen = function() {
		var percentage = getPercentage();
		percentage = Math.min(percentage, 75);
		percentage = Math.max(percentage, 25);
		percentage = Math.abs(50 - percentage);
		percentage /= 25;
		return 255 * (1 - Math.max(percentage, 0));
	};
}]);

