(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', '$uibModal', 'inventorySvc', 'transactionSvc'];
	function controller($scope, $uibModal, inventorySvc, transactionSvc) {
		var vm = this;
		vm.inventory = $scope.inventory;
		vm.transactions = [];

		function refreshTransactions() {
			vm.loadingTransactions = true;
			vm.transactions = [];
			transactionSvc
				.filterByInventoryId(vm.inventory.id)
				.success(function (data) {
					if (data.transactions.length === 0) {
						$scope.$parent.$close();
					} else {
						angular.copy(data.transactions, vm.transactions);
					}
				})
				.finally(function(){vm.loadingTransactions = false;});
		}
		refreshTransactions(); // initial call

		vm.save = save;
		vm.deleteTransaction = deleteTransaction;
		vm.removeInventory = removeInventory;
		vm.saving = false;
		vm.errorMessages = [];
		vm.confirmDeleteTransaction = false;
		vm.loadingTransactions = false;

		function deleteTransaction(transactionId) {
			vm.confirmDeleteTransaction = false;
			transactionSvc
				.deleteTransaction(transactionId)
				.success(refreshTransactions);
		}

		function removeInventory() {
			$uibModal.open({
				template: '<inventory-remove inventory="inventory" />',
				scope: angular.extend($scope.$new(true), { inventory: vm.inventory })
			}).closed.then(refreshTransactions);
		}

		function save() {
			vm.saving = true;
			inventorySvc.update($scope.inventory, vm.inventory)
				.success(function () {
					//Close the modal
					$scope.$parent.$close();
				})
				.error(function(data) {
					vm.errorMessages = angular.copy(data.errorMessages, vm.errorMessages);
				})
				.finally(function() {
					vm.saving = false;
				});
		}
	}
})();