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

function common_init($scope, $http, $sce, $location) {
	initSpinner();
	$scope.showError        = function(error)   { show_notification("error", error); }
	$scope.showNotification = function(message) { show_notification("info", message); }
	$scope.showSpinner      = function()        { showSpinner(); }
	$scope.hideSpinner      = function()        { hideSpinner(); }
	$scope.to_trusted       = function(html)    { return $sce.trustAsHtml(html); }
	$scope.go               = function(path)    { $location.path(path); }
	$scope.encodeValue      = function(val)     { return val; }
}

isManagerControllers.controller('listCollectionsCtrl', [
	'$scope', '$http', '$sce', '$location', '$routeParams',
	function ($scope, $http, $sce, $location, $routeParams) {
		common_init($scope, $http, $sce, $location);

		$scope.results = [];
		
		$scope.showSpinner();

		$http.get('is/listCollections.do').success(function(data) {
			$scope.hideSpinner();
			$scope.results = data;
		}).error(function() {
			$scope.showError('Error listing xmldb collections');
			$scope.hideSpinner();
	    });
	}
]);


isManagerControllers.controller('profilesCtrl', [
	'$scope', '$http', '$sce', '$location', '$routeParams',
	function ($scope, $http, $sce, $location, $routeParams) {
		common_init($scope, $http, $sce, $location);

		$scope.profiles = [];
		$scope.path = '/db/DRIVER/' + $routeParams.kind + '/' + $routeParams.type;
		
		$scope.showSpinner();
		
		$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
		$http.post('is/listProfiles.do', $.param({
			'kind' :  $routeParams.kind,
			'type' :  $routeParams.type
		})).success(function(data) {
			$scope.hideSpinner();
			$scope.profiles = data;
		}).error(function() {
			$scope.showError('Error listing xmldb collections');
			$scope.hideSpinner();
	    });
	}
]);


isManagerControllers.controller('profileCtrl', [
	'$scope', '$http', '$sce', '$location', '$routeParams',
	function ($scope, $http, $sce, $location, $routeParams) {
		common_init($scope, $http, $sce, $location);

		$scope.id = $routeParams.id;
		$scope.profile = '';
		$scope.editProfile = '';
		
		$scope.showSpinner();
		
		$http.get('is/getProfile.do?id=' + $scope.id).success(function(data) {
			$scope.hideSpinner();
			$scope.profile = data;
		}).error(function() {
			$scope.showError('Error retreiving profile');
			$scope.hideSpinner();
		});
		
		$scope.deleteProfile = function() {
			if (confirm("Are you sure ?")) {
				$scope.showSpinner();
				$http.get('is/deleteProfile.do?id=' + $scope.id).success(function(data) {
					$scope.hideSpinner();
					$scope.showNotification('Profile deleted !');
					$scope.profile = '';
				}).error(function() {
					$scope.showError('Error deleting profile');
					$scope.hideSpinner();
				});
			}
		}
		
		$scope.startEditing = function() {
			$scope.editProfile = '' + $scope.profile;
		}
		
		$scope.abortEditing = function() {
			$scope.editProfile = '';
		}

		$scope.saveEditing = function() {
			$scope.showSpinner();
			$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
			$http.post('is/updateProfile.do', $.param({
				'profile' : $scope.editProfile
			})).success(function(data) {
				$scope.hideSpinner();
				$scope.showNotification('Profile updated !');
				$scope.profile = '' + $scope.editProfile;
				$scope.editProfile = '';
			}).error(function(err) {
				$scope.showError(err.message);
				$scope.hideSpinner();
			});
		}
	}
]);


isManagerControllers.controller('schemasCtrl', [
	'$scope', '$http', '$sce', '$location', '$routeParams',
	function ($scope, $http, $sce, $location, $routeParams) {
		common_init($scope, $http, $sce, $location);

		$scope.schemas = [];
		
		$scope.showSpinner();

		$http.get('is/listSchemas.do').success(function(data) {
			$scope.hideSpinner();
			$scope.schemas = data;
		}).error(function() {
			$scope.showError('Error retreiving schemas');
			$scope.hideSpinner();
	    });
	}
]);


isManagerControllers.controller('schemaCtrl', [
	'$scope', '$http', '$sce', '$location', '$routeParams',
	function ($scope, $http, $sce, $location, $routeParams) {
		common_init($scope, $http, $sce, $location);

		$scope.name = $routeParams.name;
		$scope.schema = '';

		$scope.showSpinner();
		
		$http.get('is/getSchema.do?name=' + $scope.name).success(function(data) {
			$scope.hideSpinner();
			$scope.schema = data;
		}).error(function() {
			$scope.showError('Error obtaining schema' + $scope.name);
			$scope.hideSpinner();
		});
	}
]);


isManagerControllers.controller('servicesCtrl', [
	'$scope', '$http', '$sce', '$location', '$routeParams',
    function ($scope, $http, $sce, $location, $routeParams) {
		common_init($scope, $http, $sce, $location);
		$scope.groups = [];
		$scope.subscriptions = [];
		
		$scope.showSpinner();
		$http.get('is/listServices.do').success(function(data) {
			$scope.hideSpinner();
			$scope.groups = data;
		}).error(function() {
			$scope.showError('Error obtaining services');
			$scope.hideSpinner();
		});
		
		$scope.setSubscriptions = function(subscriptions) {
			$scope.subscriptions = subscriptions;
		}
		
		$scope.pingServices = function() {
			var list = [];
			angular.forEach($scope.groups, function(group) {
				angular.forEach(group.services, function(service) {
					if (service.id && service.wsdl) {
						service.status = 'UNKNOWN';
						list.push(service);
					}
				});
			});
			$scope.ping(list, 0);
		}
		
		$scope.ping = function(list, pos) {
			if (list.length == 0)   { return; }
			if (pos >= list.length) { $scope.hideSpinner();	return;	}
			if (pos == 0)           { $scope.showSpinner(); }
			
			$http.get('is/ping.do?timeout=1500&url='+encodeURIComponent(list[pos].wsdl)).success(function(data) {
				list[pos].status = 'ACTIVE';
				$scope.ping(list, pos + 1);
			}).error(function() {
				list[pos].status = 'NOT_RESPONDING';
				$scope.ping(list, pos + 1);
			});
		}
	}
]);



isManagerControllers.controller('isQueryCtrl', [
	'$scope', '$http', '$sce', '$location', '$routeParams', 'localStorageService',
	function ($scope, $http, $sce, $location, $routeParams, localStorageService) {
		common_init($scope, $http, $sce, $location);
		
		$scope.history = localStorageService.get('xquery_history');
		if (!$scope.history) {
			$scope.history = [];
		}
		
		$scope.query = "for $x in collection('/db/DRIVER/VocabularyDSResources/VocabularyDSResourceType') return $x";
		$scope.error = null;
		$scope.results = [];

        $scope.searchXQuery = function() {
			$scope.results = [];
			$scope.error = null;
			$scope.showSpinner();
			$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
			$http.post('is/xquery.do', $.param({
				'query' : $scope.query
			})).success(function(data) {
				$scope.hideSpinner();
				$scope.results = data;
				$scope.history.push({ 'date' : new Date(), 'query' : $scope.query });
				if ($scope.history.length > 100) {
					$scope.history = $scope.history.splice($scope.history.length - 100);
				}
				localStorageService.set('xquery_history', $scope.history);
			}).error(function(err) {
				$scope.error = err;
				$scope.hideSpinner();
			});
		}
        
        $scope.updateXQuery = function(q) {
        	$scope.query = q;
        	$scope.searchXQuery(); 
        }
        
        $scope.clearHistory = function() {
        	$scope.history = [];
        	localStorageService.set('xquery_history', []);
        }
	}
]);
isManagerControllers.controller('registerProfileCtrl', [
	'$scope', '$http', '$sce', '$location', '$routeParams',
	function ($scope, $http, $sce, $location, $routeParams) {
		common_init($scope, $http, $sce, $location);

		$scope.profile = '';

		$scope.register = function() {
			$scope.showSpinner();
			$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
			$http.post('is/registerProfile.do', $.param({
				'profile' : $scope.profile
			})).success(function(id) {
				$scope.hideSpinner();
				$scope.go('/profile/' + id)
			}).error(function() {
				$scope.showError('Error registerting profile');
				$scope.hideSpinner();
		    });
		}
	}
]);


isManagerControllers.controller('bulkImporterCtrl', [
	'$scope', '$http', '$sce', '$location', '$routeParams',
	function ($scope, $http, $sce, $location, $routeParams) {
		common_init($scope, $http, $sce, $location);

		$scope.path = 'file:///tmp/dnet_import';
		$scope.schemas = true;
		$scope.profiles = true;
		
		$scope.response = {};
		
		$scope.bulkImport = function() {
			$scope.response = {};
			$scope.showSpinner();
			$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
			$http.post('is/import.do', $.param({
				'path'     : $scope.path,
				'schemas'  : $scope.schemas,
				'profiles' : $scope.profiles
			})).success(function(data) {
				$scope.hideSpinner();
				$scope.response = data;
			}).error(function() {
				$scope.showError('Error registerting profile');
				$scope.hideSpinner();
		    });
		}
	}
]);


isManagerControllers.controller('validateProvilesCtrl', [
	'$scope', '$http', '$sce', '$location', '$routeParams',
	function ($scope, $http, $sce, $location, $routeParams) {
		common_init($scope, $http, $sce, $location);
		
		$scope.metaWfId = '';
		$scope.section = '';
		$scope.family = '';
		
		$scope.getValidationMetaWfId = function() {
			$scope.metaWfId = '';
			$scope.section = '';
			$scope.family = '';
			
			$scope.showSpinner();
			$http.get('is/getMetaWfIdForFamily.do?family=IS_VALIDATION').success(function(data) {
				$scope.hideSpinner();
				$scope.metaWfId = data.id;
				$scope.section = data.section;
				$scope.family = data.family;
			}).error(function() {
				$scope.showError('Metaworkflow not registered');
                $scope.hideSpinner();
			});
		}
		
		$scope.registerValidationWfs = function() {
			$scope.metaWfId = '';
			$scope.showSpinner();
			$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
			$http.post('is/import.do', $.param({
				'path'     : 'classpath*:/eu/dnetlib/functionality/modular/workflows/validation',
				'schemas'  : false,
				'profiles' : true
			})).success(function(data) {
				$scope.hideSpinner();
				$scope.showNotification('Profiles are been registered');
				$scope.getValidationMetaWfId();
			}).error(function() {
				$scope.showError('Error registering profiles');
				$scope.hideSpinner();
		    });
		}
		
		$scope.getValidationMetaWfId();
	}
]);

isManagerControllers.controller('blackboardCtrl', [
	'$scope', '$http', '$sce', '$location', '$routeParams',
	function ($scope, $http, $sce, $location, $routeParams) {
		common_init($scope, $http, $sce, $location);
		
		$scope.refresh = function() {
			$scope.blackboards = [];
			$scope.showSpinner();
			$http.get('is/listBlackboards.do').success(function(data) {
				$scope.hideSpinner();
				$scope.blackboards = data;
			}).error(function() {
				$scope.showError('Error retreiving schemas');
				$scope.hideSpinner();
		    });
		}
		$scope.refresh();
	}
]);

isManagerControllers.controller('backupCtrl', [
	'$scope', '$http', '$sce', '$location', '$routeParams',
	function ($scope, $http, $sce, $location, $routeParams) {
		common_init($scope, $http, $sce, $location);
		
		$scope.metaWfId = '';
		$scope.section = '';
		$scope.family = '';
		
		$scope.getBackupMetaWfId = function() {
			$scope.metaWfId = '';
			$scope.section = '';
			$scope.family = '';
			
			$scope.showSpinner();
			$http.get('is/getMetaWfIdForFamily.do?family=IS_BACKUP').success(function(data) {
				$scope.hideSpinner();
				$scope.metaWfId = data.id;
				$scope.section = data.section;
				$scope.family = data.family;
			}).error(function() {
				$scope.showError('Metaworkflow not registered');
                $scope.hideSpinner();
			});
		}
		
		$scope.registerBackupWfs = function() {
			$scope.metaWfId = '';
			$scope.showSpinner();
			$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
			$http.post('is/import.do', $.param({
				'path'     : 'classpath*:/eu/dnetlib/functionality/modular/workflows/backup',
				'schemas'  : false,
				'profiles' : true
			})).success(function(data) {
				$scope.hideSpinner();
				$scope.showNotification('Profiles are been registered');
				$scope.getBackupMetaWfId();
			}).error(function() {
				$scope.showError('Error registering profiles');
				$scope.hideSpinner();
		    });
		}
		
		$scope.getBackupMetaWfId();
	}
]);
