var indexInspectorControllers = angular.module('indexInspectorControllers', ['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;
	}
}

indexInspectorControllers.directive('compileTemplate', function ($compile, $parse) {
	return {
		link: function (scope, element, attr) {
			var parsed = $parse(attr.ngBindHtml);

			function getStringValue() {
				return (parsed(scope) || '').toString();
			}

			//Recompile if the template changes
			scope.$watch(getStringValue, function () {
				$compile(element, null, -9999)(scope);  //The -9999 makes it skip directives so that we do not recompile ourselves
			});
		}
	}
});


indexInspectorControllers.controller('indexmanageController', [
	'$scope', '$http', '$sce', '$location',
	function ($scope, $http, $sce, $location) {
		common_init($scope, $http, $sce, $location);


	}]);

indexInspectorControllers.controller('indexdbqController', ['$scope',
	'$http', '$sce', '$location', function ($scope, $http, $sce, $location) {
		common_init($scope, $http, $sce, $location);
		$scope.mdFormats = []
		$scope.backends = []
		$scope.indices = []
		$scope.query = '*=*'
		$scope.from = 0
		$scope.size = 10
		$scope.error = null;

		$scope.showSpinner();

		$scope.to_trusted = function (html_code) {
			return $sce.trustAsHtml(html_code);
		}


		$http.get('index/indexMetadataFormats.do').success(function (data) {
			$scope.hideSpinner();
			$scope.mdFormats = data;
		}).error(function () {
			$scope.showError('Error listing xmldb collections');
			$scope.hideSpinner();
		});

		$http.get('index/backend.do').success(function (data) {
			$scope.hideSpinner();
			$scope.backends = data;
		}).error(function (error) {
			$scope.showError(error.message);
			$scope.hideSpinner();
		});

		$scope.backendSelected = function (index) {

			if ($scope.selectedbackend != null) {
				$http.get('index/indexDatastructures.do', {
					params: {
						backend: $scope.selectedbackend
					}
				}).success(function (data) {
					$scope.hideSpinner();
					$scope.indices = data

				}).error(function () {
					$scope.showError('Error listing xmldb collections');
					$scope.hideSpinner();
				});
			}


		}


		$scope.hideSpinner();

		$scope.startDelete = function () {
			$scope.from = 0;
			$scope.size = 10
			$scope.deleteByQuery()
		}


		$scope.deleteByQuery = function () {

			if (($scope.selectedMdref == null) || ($scope.selectedbackend == null)) {
				alert("You must select a metadata format and a backend identifier")
				return;
			}

			$scope.showSpinner();
			$scope.error = null;
			$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
			var selectedId = null;
			if ($scope.selectedIndex != null)
				selectedId = $scope.selectedIndex.id
			$http.post('index/delete.do', $.param({

				'backend': $scope.selectedbackend,
				'format': $scope.selectedMdref.format,
				'layout': $scope.selectedMdref.layout,
				'interpretation': $scope.selectedMdref.interpretation,
				'query': $scope.query,
				'indexidentifier': selectedId

			}))
				.success(function (data) {
					$scope.hideSpinner();
					$scope.searchResult = data
					console.log(data)
				}).error(function (error) {
				$scope.error = error;
				$scope.hideSpinner();
			});
		}

		$scope.nextPage = function () {
			if ($scope.searchResult == null)
				return;
			if ($scope.from > $scope.searchResult.total)
				return;
			$scope.from += 10;
			$scope.size = $scope.from + 10
			$scope.search()
		}

		$scope.prevPage = function () {
			if ($scope.from <= 0) {
				return;
			}

			$scope.from -= 10;
			$scope.size -= 10
			$scope.search()
		}

		$scope.range = function (n) {
			return new Array(n);
		};


	}]);


indexInspectorControllers.controller('indexBrowseController', [
	'$scope', '$http', '$sce', '$location',
	function ($scope, $http, $sce, $location) {
		common_init($scope, $http, $sce, $location);
		$scope.showSpinner();
		$scope.mdFormats = []
		$scope.backends = []
		$scope.indices = []
		$scope.query = '*=*'
		$scope.error = null;

		$scope.browseFields = [];
		$scope.addedBrowseFields = [];
		$scope.selectedMdref = "";

		$http.get('index/indexMetadataFormats.do').success(function (data) {
			$scope.hideSpinner();
			$scope.mdFormats = data;
		}).error(function () {
			$scope.showError('Error listing xmldb collections');
			$scope.hideSpinner();
		});

		$http.get('index/backend.do').success(function (data) {
			$scope.hideSpinner();
			$scope.backends = data;
		}).error(function (error) {
			$scope.showError(error.message);
			$scope.hideSpinner();
		});

		$scope.backendSelected = function (index) {

			if ($scope.selectedbackend != null) {
				$http.get('index/indexDatastructures.do', {
					params: {
						backend: $scope.selectedbackend
					}
				}).success(function (data) {
					$scope.hideSpinner();
					$scope.indices = data

				}).error(function () {
					$scope.showError('Error listing xmldb collections');
					$scope.hideSpinner();
				});
			}


		}

		$scope.metadataFormatSelected = function (index) {
			if ($scope.selectedMdref == null) {
				$scope.addedBrowseFields = [];
				$scope.browseFields = []
				return;
			}

			$http.get('index/mdFormatInfo.do', {
				params: {
					id: $scope.selectedMdref.id,
					layout: $scope.selectedMdref.layout
				}
			}).success(function (data) {
				$scope.hideSpinner();
				$scope.browseFields = data;
				$scope.browseFields.sort()
				$scope.addedBrowseFields = [];
				$scope.selectedBrowser = '--- Add Field --'
			}).error(function () {
				$scope.showError('Error listing xmldb collections');
				$scope.hideSpinner();
			});
		};

		$scope.startBrowse = function () {

			if (($scope.selectedMdref == null) || ($scope.selectedbackend == null)) {
				alert("You must select a metadata format and a backend identifier")
				return;
			}
			if ($scope.addedBrowseFields.length == 0) {
				alert("You must select at least one browse field")
				return;
			}
			$scope.showSpinner();
			$scope.error = null;
			$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
			$http.post('index/browse.do', $.param({

				'backend': $scope.selectedbackend,
				'format': $scope.selectedMdref.format,
				'layout': $scope.selectedMdref.layout,
				'interpretation': $scope.selectedMdref.interpretation,
				'fields': JSON.stringify($scope.addedBrowseFields),
				'query': $scope.query
			}))
				.success(function (data) {
					$scope.hideSpinner();
					$scope.browseResult = data
				}).error(function (error) {
				$scope.error = error;
				$scope.hideSpinner();
			});
		}


		$scope.deleteBrowseField = function (item) {
			var i = 0

			for (; i < $scope.addedBrowseFields.length; i++) {
				if ($scope.addedBrowseFields[i] == item)
					break;
			}
			$scope.addedBrowseFields.splice(i, 1)
			$scope.browseFields = $scope.browseFields.concat(item)
			$scope.browseFields.sort();

		}

		$scope.browseFieldAdded = function () {
			for (i = 0; i < $scope.browseFields.length; i++) {
				if ($scope.browseFields[i] == $scope.selectedBrowser) {
					var data = $scope.browseFields[i];
					$scope.addedBrowseFields = $scope.addedBrowseFields.concat(data)
					$scope.browseFields.splice(i, 1)
					return;
				}
			}
		}


	}]);

function replaceText(str) {
	var str1 = String(str);

	return str1.replace(/\n/g, "<br/>");
}


function constructMDREFfromString(input) {
	if (input == null || input.length == 0)
		return null;
	var mdrefArr = input.split('-');
	if (3 == mdrefArr.length) {
		var x = [];
		x['format'] = mdrefArr[0];
		x['layout'] = mdrefArr[1];
		x['interpretation'] = mdrefArr[2];
		return x;
	}
}


function counstructStringMDREF(item) {
	if (item != null && item.hasOwnProperty('format') && item.hasOwnProperty('layout') && item.hasOwnProperty('interpretation'))
		return item.format + '-' + item.layout + '-' + item.interpretation;

	return null;
}


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

		$scope.mdFormats = []
		$scope.backends = []
		$scope.indices = []
		$scope.query = '*=*'
		$scope.from = 0
		$scope.size = 10
		$scope.error = null;
		console.log("Valore location");


		if ($routeParams['backend'] != null && $routeParams['backend'].length > 0) {
			$scope.selectedbackend_param = $routeParams['backend'];
			$scope.selectedIndex_param = $routeParams['index'];
			$scope.selectedMdref_param = constructMDREFfromString( $routeParams['mdformat']);
			var selectedMdref_param = $routeParams['mdformat'];
			$scope.start_param =  $routeParams['start'];
			$scope.query_param =  $routeParams['query'];

			$scope.query = $scope.query_param

			$scope.showSpinner();
			$scope.error = null;
			$scope.size = 10;
			$scope.from = $scope.start_param;

			$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
			var selectedId = null;
			if ($scope.selectedIndex != null)
				selectedId = $scope.selectedIndex.id
			$http.post('index/search.do', $.param({

				'backend': $scope.selectedbackend_param,
				'format': $scope.selectedMdref_param.format,
				'layout': $scope.selectedMdref_param.layout,
				'interpretation': $scope.selectedMdref_param.interpretation,
				'query': $scope.query_param,
				'from': $scope.start_param,
				'number': $scope.size,
				'indexidentifier': ""
			}))
				.success(function (data) {
					$scope.hideSpinner();
					$scope.searchResult = data
					console.log(data)
				}).error(function (error) {
				$scope.error = error;
				$scope.hideSpinner();
			});
		}

		console.log(selectedMdref_param);

		$scope.showSpinner();

		$scope.to_trusted = function (html_code) {
			return $sce.trustAsHtml(html_code);
		}


		$http.get('index/indexMetadataFormats.do').success(function (data) {
			$scope.hideSpinner();
			$scope.mdFormats = data;

			if (selectedMdref_param != null) {
				$scope.mdFormats.forEach(function (item) {
					var mdref = counstructStringMDREF(item);

					if (mdref === selectedMdref_param) {
						$scope.selectedMdref = item;
					}
				})
			}


		}).error(function () {
			$scope.showError('Error listing xmldb collections');
			$scope.hideSpinner();
		});

		$http.get('index/backend.do').success(function (data) {
			$scope.hideSpinner();
			$scope.backends = data;
			if ($scope.selectedbackend_param != null) {
				$scope.backends.forEach(function (item) {
					if (item === $scope.selectedbackend_param) {
						$scope.selectedbackend = item;
					}
				})
			}



		}).error(function (error) {
			$scope.showError(error.message);
			$scope.hideSpinner();
		});

		$scope.backendSelected = function (index) {

			if ($scope.selectedbackend != null) {
				$http.get('index/indexDatastructures.do', {
					params: {
						backend: $scope.selectedbackend
					}
				}).success(function (data) {
					$scope.hideSpinner();
					$scope.indices = data

				}).error(function () {
					$scope.showError('Error listing xmldb collections');
					$scope.hideSpinner();
				});
			}


		}


		$scope.hideSpinner();

		$scope.startSearch = function () {
			$scope.from = 0;
			$scope.size = 10
			$scope.search()
		}


		$scope.share = function () {
			var currentUrl = $location.$$absUrl;
			console.log(currentUrl);
			var path = $location.$$path;
			currentUrl = currentUrl.replace(path, "");
			if ($scope.selectedIndex != null)
				selectedId = $scope.selectedIndex.id
			else
				selectedId = "ALL"
			var shareUrl = currentUrl + "/query/" + counstructStringMDREF($scope.selectedMdref) + "/" + $scope.selectedbackend + "/" + selectedId + "/" + $scope.from + "/" + $scope.query;
			window.prompt("Copy to clipboard: Ctrl+C, Enter", shareUrl);
		}


		$scope.search = function () {
			if (($scope.selectedMdref == null) || ($scope.selectedbackend == null)) {
				alert("You must select a metadata format and a backend identifier")
				return;
			}

			$scope.showSpinner();
			$scope.error = null;
			$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
			var selectedId = null;
			if ($scope.selectedIndex != null)
				selectedId = $scope.selectedIndex.id
			$http.post('index/search.do', $.param({

				'backend': $scope.selectedbackend,
				'format': $scope.selectedMdref.format,
				'layout': $scope.selectedMdref.layout,
				'interpretation': $scope.selectedMdref.interpretation,
				'query': $scope.query,
				'from': $scope.from,
				'number': $scope.size,
				'indexidentifier': selectedId
			}))
				.success(function (data) {
					$scope.hideSpinner();
					$scope.searchResult = data
				}).error(function (error) {
				$scope.error = error;
				$scope.hideSpinner();
			});
		}

		$scope.nextPage = function () {
			if ($scope.searchResult == null)
				return;
			if ($scope.from > $scope.searchResult.total)
				return;
			$scope.from += 10;
			$scope.size = $scope.from + 10
			$scope.search()
		}

		$scope.prevPage = function () {
			if ($scope.from <= 0) {
				return;
			}

			$scope.from -= 10;
			$scope.size -= 10
			$scope.search()
		}

		$scope.range = function (n) {
			return new Array(n);
		};


	}]);

