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

repoControllers.controller('repoBrowseCtrl', [
	'$scope', '$http', '$timeout', '$sce', '$location',
	function ($scope, $http, $timeout, $sce, $location) {
		common_init($scope, $http, $sce, $location);
		$scope.repoBrowseFields = getBrowseFields();
		
		$scope.sortType     = 'term';
		$scope.sortReverse  = false;
		
		$scope.repoBrowseData = { 'data' : [] };
			
		$scope.searchApis = function (text) {
			$scope.go('/list/__SEARCH__/' + text); 
		} 
		
		$scope.browseApis = function (field, value) {
			$('#showRepoBrowseData').modal('hide');
			$scope.showSpinner();
			$timeout(function() {
				$scope.go('/list/' + field + '/' + value);
			}, 1500);
		}
		
		$scope.browseRepoField = function(field) {
			$scope.repoBrowseData = {
				'label' : field.label,
				'id' :    field.id,
				'data'  : []
			};
			$scope.showSpinner();
	      	$http.get('browseRepoField.do?field=' + field.id).success(
	            function(data) {
	            	$scope.hideSpinner();
	            	$scope.repoBrowseData.data = data;
	            	$('#showRepoBrowseData').modal('show');
	            }
	        ).error(
	            function() {
	            	$scope.showError('Something really bad must have happened to our fellow hamster..');
	            	$scope.hideSpinner();
	            }
	        );
		};
	}
]);

repoControllers.controller('repoListCtrl', [
	'$scope', '$http', '$timeout', '$sce', '$routeParams', '$location',
	function ($scope, $http, $timeout, $sce, $routeParams, $location) {
		common_init($scope, $http, $sce, $location);

		$scope.sortType     = 'repoName';
		$scope.sortReverse  = false;
		$scope.apis = [];		
    	$scope.currentApiSelectionParam = $routeParams.param;
    	$scope.currentApiSelectionValue = $routeParams.value;
    	
    	$scope.updateApis = function(refresh) {
			$scope.showSpinner();
						    
			var params = {
				'param' : $scope.currentApiSelectionParam,
				'value' : $scope.currentApiSelectionValue
			};
			if (refresh) {
				params.refresh = 1;
			}

			$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
			$http.post('listApis.do', $.param(params)).success(
	            function(data) {
	            	$scope.hideSpinner();
	            	$scope.apis = data;
	            }
	        ).error(
	            function() {
	            	$scope.showError('Something really bad must have happened to our fellow hamster..');
	            	$scope.hideSpinner();
	            }
	        );
    	};
        	
    	$scope.updateApis(false);
	}
]);

repoControllers.controller('repoApiCtrl', [
	'$scope', '$http', '$timeout', '$sce', '$routeParams', '$location',
	function ($scope, $http, $timeout, $sce, $routeParams, $location) {
		common_init($scope, $http, $sce, $location);
		
		commonInitialize($scope, $http, $sce);
		wf_init($scope, $http, $sce);
		
		$scope.availableRepohiWfs = getAvailableRepohiWfs();
		$scope.compatibilityLevels = getCompatibilityLevels();
		
		$scope.validatorBlacklistAddress = '';
		$scope.validatorBlacklistAddress = '';
    			
		$scope.currentRepoApi = {};
		$scope.currentSets = [];
		$scope.selectedSets = [];
    	
    	$scope.loadApi = function() {
    		$scope.showSpinner();
    		$(".btnRefreshApi").attr("disabled", "disabled");
    		$http.get('repoApi.get?repoId=' + $routeParams.repoId + "&ifaceId=" +  $routeParams.ifaceId)
            .success(
                function(data) {
                	$scope.currentRepoApi = data;
                	$scope.metaworkflows = data.metaWFs;

                	angular.forEach(data.otherParams, function(term){
                		if (term.id == 'last_validation_job') {
                			if (getValidatorAddress()) {
                				$scope.validatorDetailsAddress = getValidatorAddress() + "/prepareSummary.action?jobId=" + term.value;
                			}
                			if (getValidatorServiceAddress()) {
                				$scope.validatorBlacklistAddress = getValidatorServiceAddress() + "/workflows?request=GetBlacklistedRecords&datasourceId=" + $routeParams.repoId;
                			}
                		}                                       
                	});
                	
                	if (data.protocol == 'oai') {
    	            	var found = false;
    	            	angular.forEach(data.accessParams, function(param, pos){
    	                    if (param.name == 'set') {
    	                    	$scope.listSets($scope.currentRepoApi.accessParams);
    	                    }
    	        		});
                	}
                	$scope.hideSpinner(); 
                	            	
                	$(".btnRefreshApi").removeAttr("disabled");
                	
                	if ($routeParams.metawf != 'ALL' && $routeParams.wf != 'ALL') {
                		$scope.getAtomicWorkflowAndMetaWf($routeParams.metawf, $routeParams.wf);
                		$timeout(function() {
                			$("#collapse_" + $routeParams.metawf.substring(0, 36)).collapse('show');
                		}, 2000);
                	}
                }
            ).error(
                function() {
                	$scope.showError('Something really bad must have happened to our fellow hamster..');
                	$scope.hideSpinner();
                }
            );
    	};
    	
    	
    	$scope.removeApi = function() {
    		if (confirm("You are deleting the current API.\n\nAre you sure?")) {
	    		$scope.showSpinner();
	    		$http.get('repoApi.delete?repo=' + $routeParams.repoId + "&iface=" +  $routeParams.ifaceId).success(function(data) {
	    			alert("The API has been deleted !!!");
	    			$scope.hideSpinner();
	    			$scope.go("/browse");
	    		}).error(function(err) {
	    			$scope.showError('Error removing API: '  + err.message);
	    			$scope.hideSpinner();
	    		});
    		}
    	};
   	
    	
		$scope.newDataProviderWorkflow = function (wf) {
			
			if (wf == undefined) {
				$scope.showError('Please choose a workflow !');
	    		return;
			}
			
			$scope.showSpinner();
	
			$scope.metaworkflows.push({"id":"","name":"Waiting...","status":"MISSING","progress":0});
	    				
			$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
			$http.post('repoMetaWf.new', $.param({
				'wf'    : wf,
				'iface' : $scope.currentRepoApi.id,
				'id'    : $scope.currentRepoApi.repoId, 
				'name'  : $scope.currentRepoApi.repoName
			})).success(
	       			function(data) {
	       				$scope.hideSpinner();
	       				$(".btnRefreshApi").attr("disabled", "disabled");
	       				$timeout(function () { $scope.loadApi() }, 7000);
		            }
	       	).error(
	       			function() {
	       				$scope.showError('Something really bad must have happened to our fellow hamster..');
	       				$scope.hideSpinner();
		           }
	       	);
		};
		
		$scope.destroyDataProviderWorkflow = function (metaWf) {
			
			if (metaWf.destroyWorkflow == undefined) {
				$scope.showError('Destroy wf is missing !');
	    		return;
			}
			
			if (!confirm("Are you sure ?")) {
				return;
			}
					
			$scope.showSpinner();
			
			metaWf.deleting = true;
			
			$http.get('repoMetaWf.destroy?destroyWf=' + metaWf.destroyWorkflow)
	       	.success(
	       			function(data) {
	       				$scope.hideSpinner();
	       				$(".btnRefreshApi").attr("disabled", "disabled");
	       				$timeout(function () { $scope.loadApi() }, 7000);
		            }
	       	).error(
	       			function() {
	       				$scope.showError('Something really bad must have happened to our fellow hamster..');
	       				$scope.hideSpinner();
		           }
	       	);
		};
		
		$scope.testOAI = function (params) {
			angular.forEach(params, function(param, pos){
	            if (param.name == 'baseUrl') {
	            	location.href = "oaiExplorer.do?oaiBaseUrl=" + param.value;
	            }
			});
		}
	
		$scope.prepareUpdateRepoApi = function() {
			$scope.tempAccessParams = angular.copy($scope.currentRepoApi.accessParams); 

			$scope.tempMdIdPath = '';
			angular.forEach($scope.currentRepoApi.otherParams, function(param, pos){
	            if (param.name == 'metadata_identifier_path') {
	            	$scope.tempMdIdPath = param.value;
	            }
			});
		}
		
		
		$scope.updateRepoApi = function() {
			$scope.showSpinner();
	
			var map = {};
			angular.forEach($scope.tempAccessParams, function(param, pos){
	            if (param.name) {
	            	map[param.name] = param.value
	            }
			});
			
			$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
	        $http.post('repoApi.update', $.param({
	      		'id'           : $scope.currentRepoApi.repoId,
	      		'iface'        : $scope.currentRepoApi.id,
	      		'mdIdPath'     : $scope.tempMdIdPath,
	      		'accessParams' : JSON.stringify(map)
	      	})).success(function(data) {
	      		$scope.showNotification('Api correctly saved !');
	        	$scope.loadApi(); 
	        }).error(function(err) {
	        	$scope.hideSpinner();
	        	$scope.showError('Error updating api: ' + err.message);
	        });
		};
		
		
		$scope.updateSets = function(selection, accessParams) {
			var s = selection.join();
			angular.forEach(accessParams, function(param, pos){
	            if (param.name == 'set') {
	            	param.value = s;
	            }
			});
		}
		
		$scope.listSets = function(accessParams) {
			var baseUrl = '';
			
			$scope.selectedSets = [];
			$scope.currentSets = [];
			
			angular.forEach(accessParams, function(param, pos){
	            if (param.name == 'baseUrl') {
	            	baseUrl = param.value
	            }
	            if (param.name == 'set') {
	            	$scope.selectedSets = param.value.split(",");
	            }
			});
			
			if (!baseUrl) {
				$scope.showError("baseUrl param is missing");
				return;
			}

			$scope.showSpinner();
			$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
	        $http.post("listValidValuesForParam.do", $.param({
	        	'protocol' : 'oai',
	        	'param'    : 'set',
	        	'baseUrl'  : baseUrl
	        })).success(function(data) {
				$scope.hideSpinner();
	        	$scope.currentSets = data;
	        	angular.forEach($scope.currentSets, function(curr, pos1) {
		        	angular.forEach($scope.selectedSets, function(sel, pos2) {
		        		if (curr.id.trim() == sel.trim()) {
		        			curr.selected = true;
		        		}
		        	});
				});
	        }).error(function() {
				$scope.hideSpinner();
				$scope.showError("baseUrl param is missing");
			});
	        
		};
		
		
		$scope.verifyMetaWf = function(ds, wf) {
			var compliance = '';
			var type = '';
			angular.forEach(ds.commonParams, function(p,pos) {
	        	if (p.id == 'compliance') {
	        		compliance = p.value;
	        	}
	        	if (p.id == 'typology') {
	        		type = p.value;
	        	}
			});
			
			return (compliance && type && $scope.isValidTerm(compliance, wf.compliances) && $scope.isValidTerm(type, wf.ifaceTypes)); 
		}

		$scope.isValidTerm = function(term, list) {
			
			if (list.length == 0) {
				return true;
			}
			var res = false;
			angular.forEach(list, function(curr,pos) {
	        	if (term.lastIndexOf(curr, 0) === 0) { // implementation of term.startsWith(curr)
	        		res = true;
	        	}
			});
			return res;
		}

		$scope.overrideApiCompliance = function(level) {
			$scope.showSpinner();
			$http.get('repoApiCompliance.update?id=' + $scope.currentRepoApi.repoId + '&iface=' + $scope.currentRepoApi.id + '&compliance=' + level)
	        .success(
	        		function(data) {
	        			$scope.hideSpinner();
	        			$scope.showNotification('Api correctly updated !');
	        			$scope.loadApi(); 
	        		}
	        ).error(
	        		function() {
	        			$scope.showError('Something really bad must have happened to our fellow hamster..');
	        			$scope.hideSpinner();
	        		}
	        );
		}
		
		$scope.resetApiCompliance = function() {
			$scope.showSpinner();
			$http.get('repoApiCompliance.reset?id=' + $scope.currentRepoApi.repoId + '&iface=' + $scope.currentRepoApi.id)
	        .success(
	        		function(data) {
	        			$scope.hideSpinner();
	        			$scope.showNotification('Api correctly updated !');
	        			$scope.loadApi(); 
	        		}
	        ).error(
	        		function() {
	        			$scope.showError('Something really bad must have happened to our fellow hamster..');
	        			$scope.hideSpinner();
	        		}
	        );
		}
				
    	$scope.loadApi();
	}
		
 ]);

