(function() {
	window.app.factory("inventorySvc",
	[
		"$http", "$filter", 'Upload',
		function($http, $filter, Upload) {
			var inventories = [];

			loadInventories();

			var svc = {
				add: add,
				distribute: distribute,
				update: update,
				remove: remove,
				inventories: inventories,
				get: get,
				refresh: refresh,
				load: load,
				exportInventory: exportInventory,
				isShredReady: isShredReady,
				importFile: importFile
			};

			return svc;

			function loadInventories() {
				$http.post("/Inventory/All")
					.success(function(data) {
						angular.copy(data, inventories);
					});
			}

			function exportInventory() {
				return $http.post("/Inventory/Export", {}, { responseType: "arraybuffer" });
			}

			function add(inventory) {
				return $http.post("/Inventory/Add", inventory)
					.success(function(inventory) {
						inventories.unshift(inventory);
					});
			}

			function distribute(distribution) {
				return $http.post("/Inventory/Distribute", distribution)
					.success(function(data) {
						angular.copy(data, inventories);
					});
			}

			function update(existingInventory, updatedInventory) {
				return $http.post("/Inventory/Update", updatedInventory)
					.success(function(inventory) {
						angular.extend(existingInventory, inventory);
					});
			}

			// remove quantity from this inventory
			function remove(removeForm) {
				var existingInventory = get(removeForm.inventoryId);
				return $http.post("/Inventory/Remove", removeForm)
					.success(function(data) {
						angular.copy(data, existingInventory);
					});
			}

			function get(id) {
				var results = $filter("filter")(inventories, { id: id });
				if (results.length > 0)
					return results[0];
				return null;
			}

			// refresh this inventory from the server
			function refresh(id) {
				var existingInventory = get(id);
				if (existingInventory) {
					load(id)
						.success(function(inventory) {
							angular.copy(inventory, existingInventory);
						});
				}
			}

			function load(id) {
				return $http.post("/Inventory/Find", { id: id })
					.success(function (inventory) {
						var existingInventory = get(id);
						if (existingInventory != null)
							angular.copy(inventory, existingInventory);
						else
							inventories.unshift(inventory);
					});
			}

			function importFile(file) {
				return Upload.upload({
					url: "/api/Import",
					method: 'POST',
					data: { file: file}
				});
			}

			function isShredReady(inventory) {
				return new Date(inventory.shredReadyDate) <= new Date();
			}
		}
	]);
})();