var module = angular.module('shutdownUI', []);

module.controller('shutdownCtrl', function ($scope, $http) {
	$scope.stoppables = [];
	
	$scope.stopLaunched = false;
	$scope.stopEnded = false;
	
	initSpinner();
	
	$scope.loadStoppables = function() {
		showSpinner();
		$scope.stoppables = [];
		$http.get('shutdown/listStoppableDetails.json').success(function(data) {
			hideSpinner();
			$scope.stoppables = data;
			$scope.calculateStatus();
		}).error(function() {
			show_notification("error","An error occurred while fetching stoppable modules");
			hideSpinner();
		});
	}
	
	$scope.calculateStatus = function() {
		var lauched = true;
		var ended = true;
		angular.forEach($scope.stoppables, function(value, key) {
			if (value.status == 'RUNNING') {
				lauched = false;
			}
			if (value.status != 'STOPPED') {
				ended = false;
			}
		});
		$scope.stopLaunched = lauched;
		$scope.stopEnded = ended;
	}
		
	$scope.prepareShutdown = function() {
		if (confirm("Are you sure ?")) {
			showSpinner();
			$scope.stoppables = [];
			$http.get('shutdown/stopAll.do').success(function(data) {
				hideSpinner();
				$scope.stopLaunched = true;
				show_notification("info", "You will be able to stop the web application soon");
				$scope.loadStoppables();
			}).error(function() {
				show_notification("error","An error occurred while fetching stoppable modules");
				hideSpinner();
			});
		}
	}
	
	$scope.resumeShutdown = function() {
		if (confirm("Are you sure ?")) {
			showSpinner();
			$scope.stoppables = [];
			$http.get('shutdown/resumeAll.do').success(function(data) {
				hideSpinner();
				$scope.stopLaunched = false;
				show_notification("info", "Resuming stopped modules");
				$scope.loadStoppables();
			}).error(function() {
				show_notification("error","An error occurred while fetching stoppable modules");
				hideSpinner();
			});
		}
	}
	
	$scope.loadStoppables();

});
