(function() {
	"use strict";

	window.app.directive('inventoryImport',
		function() {
			return {
				templateUrl: '/inventory/template/inventoryImport.tmpl.cshtml',
				controller: controller,
				controllerAs: 'vm'
			};
		});

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

		vm.uploading = false;
		vm.file = "";

		vm.statusMessage = "Import inventory items below.";
		vm.errorMessages = [];

		// upload later on form submit or something similar
		vm.submit = function () {
			if (vm.form.file.$valid && vm.file) {
				vm.upload(vm.file);
			}
		};

		// upload on file select or drop
		vm.upload = function(file) {
			vm.uploading = true;
			inventorySvc
				.importFile(file)
				.then(function(resp) {
					console.log("Success " + resp.config.data.file.name + "uploaded. Response: " + resp.data);
					vm.uploading = false;
					},
					function (resp) {
						if (angular.isArray(resp.data))
							angular.copy(resp.data, vm.errorMessages);
						else
							angular.copy([resp.data], vm.errorMessages);
						console.log("Error status: " + resp.status + " message: " + resp.data);
						vm.uploading = false;
					},
					function(evt) {
						var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
						console.log("progress: " + progressPercentage + "% " + evt.config.data.file.name);
					});
		};

	}
})();