(function() {
	"use strict";

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

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

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

		vm.saving = false;
		vm.inventory = {};
		vm.inventoryTypes = inventoryTypeSvc.inventoryTypes;
		vm.errorMessage = null;
		vm.quantity = quantity;

		function quantity() {
			vm.inventory.quantity =
				$scope.palletCount * $scope.casesPerPallet + $scope.caseCount;
			return vm.inventory.quantity;
		}

		function add() {
			vm.saving = true;
			inventorySvc.add(vm.inventory)
				.success(function () {
					//Close the modal
					$scope.$close();
				})
				.error(function(data) {
					vm.errorMessage = 'There was a problem adding the inventory: ' + data;
				})
				.finally(function() {
					vm.saving = false;
				});
		}

		$scope.$watch('commodity', function (newValue, oldValue) {
			if (newValue)
				vm.inventory.inventoryTypeId = newValue.id;
		});
	}
})();