angular.module("robware").controller("weight", ["$scope", "weightService", function($scope, weightService) {
		$scope.submitting = false;
		$scope.weight = null;
		$scope.fat = null;

		$scope.readings = [];
		$scope.headings = {weight: "Weight (KG)", fat: "Fat %", bmi: "BMI"};

		function refreshReadings() {
			weightService.getReadings().then(function(data) {
				$scope.readings = data;
			});
		}

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

		$scope.addReading = function() {
			if (!$scope.weight || !$scope.fat)
				return;

			$scope.submitting = true;
			weightService.addWeight($scope.weight, $scope.fat).then(function(data) {
				refreshReadings();
				$scope.submitting = false;
				$scope.weight = null;
				$scope.fat = null;
			});
		};

		$scope.deleteReading = function(id) {
			weightService.deleteWeight(id).then(function() {
				refreshReadings();
			});
		};

		Object.defineProperty($scope, "tenLatestReadings", {
			get: function() {
				var temp = $scope.readings.slice(-10);
				temp.reverse();
				return temp;
			}
		});
	}]);

