(function() {
	"use strict";

	window.app.directive('inventoryDistribute', inventoryDistribute);

	function inventoryDistribute() {
		return {
			templateUrl: '/inventory/template/inventoryDistribute.tmpl.cshtml',
			controller: controller,
			controllerAs: 'vm'
		}
	}

	controller.$inject = ['$scope', 'inventorySvc'];
	function controller($scope, inventorySvc) {
		var vm = this;

		vm.save = save;
		vm.saving = false;
		vm.quantities = angular.copy(inventorySvc.inventories);
		vm.distribution = {};
		vm.errorMessages = [];

		function getInventoryDistributeQuantities(inventory) {
			var invQty = [];
			inventory.forEach(function (i) {
				if (i.distributeQuantity > 0)
					invQty.push({ inventoryId: i.id, quantity: i.distributeQuantity });
			});
			return invQty;
		}

		function save() {
			vm.saving = true;
			vm.distribution.inventoryQuantities = getInventoryDistributeQuantities(vm.quantities);
			inventorySvc.distribute(vm.distribution)
				.success(function () {
					//Close the modal
					$scope.$close();
				})
				.error(function(data) {
					vm.errorMessages = angular.copy(data.errorMessages, vm.errorMessages);
				})
				.finally(function() {
					vm.saving = false;
				});
		}
	}
})();