angular.module("robware").controller('galleryUpload', ["$scope", "$http", function($scope, $http) {
	$scope.images = [];
	$scope.contextMenuActions = {
		Remove: remove,
		Clear: clear
	};

	function remove(containerScope) {
		if (!containerScope.image)
			return;

		var index = $scope.images.indexOf(containerScope.image);
		if (index !== -1)
			$scope.images.splice(index, 1);
	}

	function clear() {
		if (confirm("Are you sure you want to clear the uploads?"))
			$scope.images = [];
	}

	function removeImages(toRemove) {
		// I need this roundabout way to work with Angular's view engine
		var imageReferences = [];
		angular.forEach(toRemove, function(index) {
			imageReferences.push($scope.images[index]);
		});
		angular.forEach(imageReferences, function(ref) {
			$scope.images.splice($scope.images.indexOf(ref), 1);
		});
	}

	$scope.getTotalImageSize = function() {
		var totalSize = 0;
		angular.forEach($scope.images, function(image) {
			totalSize += image.file.size;
		});
		return totalSize;
	}

	$scope.safeUploadSize = function() {
		return $scope.maxUploadSize * 0.95;
	}

	$scope.fileDrop = function(files) {
		angular.forEach(files, function(file) {
			var imageObject = {
				file: file,
				title: file.name.replace(/\.[^/.]+$/, ""),
				description: "",
				preview: ""
			};

			var reader = new FileReader();
			reader.onload = function(e) {
				imageObject.preview = e.target.result;
				$scope.$apply();
			};
			reader.readAsDataURL(file);

			$scope.images.push(imageObject);
		});
	};

	$scope.upload = function() {
		var data = new FormData();
		var errors = [];
		angular.forEach($scope.images, function(image) {
			if (!image.title)
				errors.push("The image " + image.file.name + " doesn't have a title");
			data.append("files[]", image.file);
			data.append("title[]", image.title);
			data.append("description[]", image.description);
		});

		var totalSize = 0;
		data.getAll("files[]").forEach(function(entry){
			totalSize += entry.size;
		});
		if (totalSize>$scope.safeUploadSize())
			errors.push("Max upload size exceeded");

		if (errors.length>0){
			$scope.showErrors(errors);
			return;
		}

		$http({
			method: 'POST',
			url: '/gallery/uploadimages',
			data: data,
			showSpinner: true,
			headers: {'Content-Type': undefined},
			transformRequest: angular.identity
		}).then(function(response) {
			$scope.showErrors(response.data.errors);
			removeImages(response.data.uploaded);
		});
	};
}]);

