(function() {
	"use strict";

	window.app.directive('inventoryDistribute',
		function() {
			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.quantities = angular.copy(inventorySvc.inventories);
		vm.distribution = {};

		vm.saving = false;
		vm.statusMessage = "Enter details for the inventory distribution below.";
		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.statusMessage = null;
			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;
				});
		}
	}
})();