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

	init();

	function init(){
		if(semusiCommon.ACTIVE_APP_ID == undefined || semusiCommon.ACTIVE_APP_ID==""){
   		window.location =  "/dashboard";
	      	return;
	    }	

	    $scope.childApps = [];
	    $scope.currentPage = 1;
        $scope.startFrom = 0;
        $scope.pageSize = 7;
	    getChildApps();
	    getAppDetails();
	}


	function getChildApps(){
		promise = appIceService.getChildApps();
    	promise.then(function(apps) {
        	$scope.childApps = apps;            
    	});
	}

	function getAppDetails(){
		promise = appIceService.getAppDetails();
    	promise.then(function(app) {
        	if(app){
        		$scope.linkingField = app.linkingField;
        	}
    	});
	}

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

	$scope.saveChildApp = function(){
		var childApp = {
			name:$scope.appname,
			childappid: $scope.childappid,
			appid:semusiCommon.ACTIVE_APP_ID
		}
    	promise = appIceService.saveChildApp(childApp);
    	promise.then(function(data) {
    		if(data.msg){
    			alert(data.msg);
    		}
    		else{
    			getChildApps();	
                $scope.cancel();
    		}    		
    	});
    }

    $scope.editChildApp = function(childApp){
    	$scope.id = childApp._id;
		$scope.appname = childApp.name;
		$scope.childappid = childApp.childappid;
		$scope.edit = true;    	
    }

    $scope.updateChildApp = function(){
		var childApp = {
			name:$scope.appname,
			childappid: $scope.childappid,
			appid:semusiCommon.ACTIVE_APP_ID
		}
    	promise = appIceService.updateChildApp(childApp,$scope.id);
    	promise.then(function(data) {
    		getChildApps();
            $scope.cancel();
    	});
    }

    $scope.deleteChildApp = function(id){
    	if(confirm("Are you sure to delete this child app.")){
    		promise = appIceService.deleteChildApp(id);
	    	promise.then(function(data) {
	    		getChildApps();
	    	});	
    	}		
    	
    }

    $scope.updateLinkingField = function(){		
    	promise = appIceService.updateLinkingField($scope.linkingField);
    	promise.then(function(data) {
    		alert("Linking field updated.");
    	});
    }

    $scope.cancel = function(){
       $scope.appname = ""; 
       $scope.childappid = "";
       $scope.id="";
       $scope.edit = false;
    }

});	