angular.module("robware").controller('galleryManage', ["$scope", "$http", function($scope, $http) {
	$scope.albums=[];
	var albumActions={};

	var moveIndex="Move selected to album";
	$scope.contextMenuActions={
		"Delete selected":deleteSelected
	};

	function getSelectedImageIds(){
		var images=[];
		angular.forEach($scope.selectedAlbum.Images, function(image){
			if (image.selected)
				images.push(image.ImageId);
		});
		return images;
	}

	function updateAlbums(data){
		var selectedId=$scope.selectedAlbum.AlbumId;
		$scope.albums=data;
		angular.forEach($scope.albums, function(album){
			if (album.AlbumId===selectedId)
				$scope.selectedAlbum=album;
		});
	}

	function deleteSelected(){
		var images=getSelectedImageIds();
		if (images.length===0 || !confirm("Are you sure you want to delete?"))
			return;

		var data={
			selectedImages:images
		};

		$http.post("/gallery/deleteimages",data).then(function(response){
			updateAlbums(response.data);
		});
	};

	function moveImages(newAlbum){
		var images=getSelectedImageIds();
		if (images.length===0)
			return;

		var data={
			selectedImages:images,
			targetAlbumId:newAlbum.AlbumId
		};
		$http.post("/gallery/move",data).then(function(response){
			updateAlbums(response.data);
		});
	}

	$scope.$watch("albums", function(){
		if ($scope.selectedAlbum===undefined)
			$scope.selectedAlbum=$scope.albums[0];

		albumActions={};
		angular.forEach($scope.albums, function(album){
			albumActions[album.AlbumTitle]=function(){
				moveImages(album);
			};
		});
		$scope.contextMenuActions[moveIndex]=albumActions;
	});

	$scope.selectImage=function(image){
		image.selected=!image.selected;
	};

	$scope.editAlbum=function(album){
		Navigate("/gallery/editablum/"+album.AlbumId);
	};
}]);

