appice.controller('globalAppModuleController',function ($scope,appIceService,$routeParams,$location) {

	init();

	function init(){		
		$scope.editMode=false;
		$scope.currentPage = 1;
        $scope.startFrom = 0;
        $scope.pageSize = 7;
		getGlobalAppModules();
	}

	$scope.editModule = function(item){
		$scope.editMode=true;
		$scope.id = item._id;
		$scope.name = item.name;
        $scope.version = item.version;
        $scope.filename = item.filename;
        $scope.arch = item.arch;
        $scope.platform = item.platform;
        $scope.pv = item.pv;
        $scope.url = item.url;
        $scope.enableall = item.enableall;
        $scope.editable = item.editable;
	}

	$scope.saveModule = function(){
		var module = getUIModule();
		if(module.enableall==undefined){
			module.enableall=false;
		}
		if(module.editable==undefined){
			module.editable=false;
		}
		var promise = appIceService.saveModule(module);
		promise.then(function(data) {
			getGlobalAppModules();
			clearFields();
		});
	}

	$scope.updateModule = function(){		
		var promise = appIceService.updateModule(angular.toJson(getUIModule()),$scope.id);
		promise.then(function(data) {
			getGlobalAppModules();
			clearFields();
		});
	}

	$scope.deleteModule =function(id){
		if(confirm("Are you sure to delete this module?")){			
			var promise = appIceService.deleteModule(id);
			promise.then(function(data) {
				getGlobalAppModules();
				clearFields();
			});	
		}		
	}

	$scope.cancel= function(){
		clearFields();
	}

	$scope.numberOfPages=function(){
        if($scope.modules){
            var totalPages = Math.ceil($scope.modules.length/$scope.pageSize);                   
            return (totalPages == 0)?1:totalPages;
        }        
    }

	function getUIModule(){
		return module = {
			"name" : $scope.name,
            "version" : $scope.version,
            "filename" : $scope.filename,
            "arch" : $scope.arch,
            "platform":$scope.platform,
            "pv":$scope.pv,
            "url" : $scope.url,
            "editable":$scope.editable,
            "enableall":$scope.enableall            
		};
	}
	function getGlobalAppModules(){
		promise = appIceService.getGlobalAppModules();
    	promise.then(function(modules) {
        	$scope.modules=modules;     	
    	});
	}
	function clearFields(){
		$scope.name="";
        $scope.version="";
        $scope.filename="";
        $scope.arch="";
        $scope.platform="";
        $scope.pv="";
        $scope.url="";        
        $scope.editMode = false; 
        $scope.editable = false;
        $scope.enableall = false;       
	}
});