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

	init();

	function init(){				
		$scope.currentPage = 1;
        $scope.startFrom = 0;
        $scope.pageSize = 7;
		getAppModules();

	}

	function getAppModules(){
		promise = appIceService.getAppModules();
    	promise.then(function(apps) {
        	$scope.apps=apps;  
        	getGlobalAppModules();   	
    	});
	}

	function getGlobalAppModules(){
		promise = appIceService.getGlobalAppModules();
    	promise.then(function(modules) {
        	$scope.modules=modules;
        	$scope.apps.forEach(function(app){
        		var data=[];
        		$scope.modules.forEach(function(module){
        			var obj = {
        				id:module._id,
        				name: module.name,
        				editable:module.editable
        			}
        			if ($.inArray(module._id, app.modules) != -1 ) {
        				obj.enabled = true;
        			}
        			else{
        				obj.enabled = false;
        			}
        			data.push(obj);
        			
        		});
        		app.modules = data;
        	});	
    	});
	}

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

    $scope.saveAppModules = function(modules,appid){
    	promise = appIceService.saveAppModules(modules,appid);
    	promise.then(function(data) {
    		alert("App modules updated.")
        	//$scope.apps=apps;  
        	//getGlobalAppModules();   	
    	});
    }
});