(function() {
	"use strict";

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

	function editInventory() {
		return {
			scope: {
				inventory: "="
			},
			templateUrl: '/inventory/template/inventoryEdit.tmpl.cshtml',
			controller: controller,
			controllerAs: 'vm'
		}
	}

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

		vm.saving = false;
		vm.inventory = angular.copy($scope.inventory);
		vm.errorMessage = null;

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