(function() {
	"use strict";

	window.app.directive('editInventory',
		function() {
			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.inventoryOriginal = angular.copy(vm.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;
					vm.inventoryOriginal = angular.copy(vm.inventory);
				});
		}
		refreshTransactions(); // initial call

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

		vm.isShredReady = function () { return inventorySvc.isShredReady(vm.inventory); };
		vm.isInInventory = function() { return vm.inventory.quantity > 0; }

		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;
				});
		}

		function cancel() {
			angular.copy(vm.inventoryOriginal, $scope.inventory);
			$scope.$parent.$dismiss();
		}
	}
})();