app.controller('reportPagamentiCtrl',

		function($scope, $http, $cookies, $window, $location, $timeout,
				$mdDialog, $q, $routeParams, $mdMedia, utilsSvc,
				userService, ReportPagamenti, UserManager,
				Upload) {

			var vm = this;

			vm.maxItems = 0;
			vm.itemsPerPage = 100;
			vm.records = [];
			vm.selectedIndex = -1;
			vm.topIndex = 0;
			vm.appVariables = {};
			
			vm.showDetails=function(record){
				$mdDialog.show({
			            templateUrl: 'templates/dettaglioReportPagamenti.html',
			            controller: 'dettaglioRecordPagamentiCtrl',
			            targetEvent: event,
			            locals: {report:record},
			            multiple: true
			        })
			}

				vm.columnWidths = [ 
					"140px", // 0
					"350px", // 1
					"350px", // 2
					"250px", // 3
					"150px", // 4
					"140px", // 5
					"140px", // 6
				];
			
				vm.getColumnWidth = // }
					// this.lastStartIdx = index;
					function(idx) {
						return {
							'width' : vm.columnWidths[idx] + 'px',
							'min-width' : vm.columnWidths[idx] + 'px',
							// 'padding-left':'6px',
							// 'padding-right':'6px',
							'margin-left' : '8px',
							'margin-right' : '8px'
						};
					}

				
			vm.getListHeight = function() {
				containerHeight = ($window.innerHeight
						- $('#container').position().top - $('#view')
						.position().top);
				return {
					'height' : containerHeight + 'px'
				};
			};

			vm.getGridItemHeight = function() {
				return utilsSvc.getGridHeight();
			}

			vm.trimData=function(str){
				if (str==null)
					return "";
				return str.substring(0,500);
			}
			
			$window.addEventListener('resize', onResize);
			function onResize() {
				$scope.$digest();
			}
			$scope.$on('$destroy', function() {
				$window.removeEventListener('resize', onResize);
			});

			$timeout(function() {
				var evt = $window.document.createEvent('UIEvents');
				evt.initUIEvent('resize', true, false, $window, 0);
				$window.dispatchEvent(evt);
			},100);
			vm.largeScreen = function() {
				return utilsSvc.largeScreen();
			}

			
			vm.uploadFile = function(file, errFiles) {
		        $scope.f = file;
		        $scope.errFile = errFiles && errFiles[0];
		        if (file) {
		            file.upload = Upload.upload({
		                url: 'rest/reportPagamenti/uploadFile',
		                data: {file: file}
		            });

		            file.upload.then(function (response) {
		                    file.result = response.data;
		                    vm.getDisposizioni();
		            }, function (response) {
		                if (response.status > 0)
		                    vm.errorMsg = response.status + ': ' + response.data;
		                utilsSvc.showMessage('Si è verificato un errore durante il caricamento: '+ response.status + ': ' + response.data);
		            }, function (evt) {
		                file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
		            });
		        }
			}


			vm.getColumnWidth = function(idx) {
				return {
					'width' : vm.columnWidths[idx] ,
					'min-width' : vm.columnWidths[idx],
					// 'padding-left':'6px',
					// 'padding-right':'6px',
					'margin-left' : '8px',
					'margin-right' : '8px'
				};
			}

			vm.getMaxListWidth = function() {
//				var res = 0;
//				for (var i = 0; i < vm.columnWidths.length; i++)
//					res += vm.columnWidths[i] + 6 + 8 + 10;
//
//				$('#container').css('width',
//						($('#header').width() + 10) + 'px');
//				return {
//					'width' : res + 'px!important;'
//				}
			}


			vm.setOrderField = function(field) {
				if (vm.filter.orderField != field)
					vm.filter.orderField = field;
				else
					vm.filter.orderField = "-" + field;

				vm.getDisposizioni();
			}


			vm.downloadFile = function(serviceUI) {
				utilsSvc.showForever('Generazione in corso...');
				ReportPagamenti.Download({id:serviceUI.idServiceUI}).$promise.then(function(data){
					utilsSvc.downloadFile('file/text',data.response,serviceUI.filenameOut);
					utilsSvc.cancelMessage();
				}).catch(function(err){
					if (err.status==404) {
						utilsSvc.cancelMessage();
						utilsSvc.showMessage('Nessun file estratto');
					}
				});
			}

			
			vm.exportExcel = function() {
				if (vm.filteredView) {
					utilsSvc.showForever('Generazione in corso...');
					DisposizioniBonifici.ExportFiltered({}, userService
							.getFilter()).$promise.then(function(data) {
						utilsSvc.downloadFile('attachment/csv',
								data.response, 'export.csv');
						utilsSvc.cancelMessage();
					}).catch(function(err){
						if (err.status==404) {
							utilsSvc.cancelMessage();
							utilsSvc.showMessage('Nessuna distinta estratta');
						}
					})
				} else {
					utilsSvc.showForever('Generazione in corso...');
					DisposizioniBonifici.Export({}, vm.filter).$promise
							.then(function(data) {
								utilsSvc.downloadFile('attachment/csv',
										data.response, 'export.csv');
								utilsSvc.cancelMessage();
							}).catch(function(err){
								if (err.status==404) {
									utilsSvc.cancelMessage();
									utilsSvc.showMessage('Nessuna distinta estratta');
								}
							})
				}
			}

			vm.infiniteItems = {
				numLoaded_ : 0,
				toLoad_ : 0,
				loading_ : false,
				lastStartIdx : -1,
				listPromise : null,
				canceler : $q.defer(),
				// Required.
				getItemAtIndex : function(index) {
					if (vm.maxItems == 0 || index>vm.maxItems)
						return null;
					if (!vm.infiniteItems.loading_)
						if (index > vm.records.length) {
							vm.infiniteItems.fetchMoreItems_(index);
							return null;
						}
					return vm.records[index];
				},
				// Required.
				// For infinite scroll behavior, we always return a
				// slightly
				// higher
				// number than the previously loaded items.
				getLength : function() {
					return vm.maxItems;

				},
				fetchMoreItems_ : function(index) {
					if (this.toLoad_ < index) {
						this.toLoad_ += vm.itemsPerPage;
						utilsSvc.showWaitMessage('Ricerca in corso...');
						
						vm.infiniteItems.loading_ = true;

						if ((vm.records.length + vm.itemsPerPage) < vm.selectedIndex)
							vm.itemsPerPage = vm.selectedIndex - vm.records.length;

						this.listPromise = ReportPagamenti.List({start : vm.records.length,size : Math.max(vm.records.length+ index,vm.itemsPerPage)}, vm.filter).$promise;

						var mod = this;
						this.listPromise.then(function(data) {
							vm.infiniteItems.loading_ = false;
							vm.infiniteItems.toLoad_=0;
							utilsSvc.cancelWaitMessage();
							vm.records = vm.records.concat(data);
							mod.numLoaded_ = vm.records.length;
							mod.lastStartIdx = vm.records.length;
							vm.topIndex = vm.selectedIndex;

						}, function(error) {
              				vm.infiniteItems.loading_ = false;
              				vm.infiniteItems.toLoad_=0;
							utilsSvc.handleHttpError(error);
						})
					}

				}
			}

			vm.getDisposizioni = function() {
				utilsSvc.showWaitMessage('Ricerca in corso...');
				ReportPagamenti.Count({},
							function(data) {
								vm.records = [];
								vm.maxItems = data.value;
								vm.infiniteItems.numLoaded_ = 0;
								vm.infiniteItems.toLoad_ = 0;
								utilsSvc.cancelWaitMessage();
									
							}, function(error) {
								utilsSvc.cancelWaitMessage();
								utilsSvc.handleHttpError(error);
							});
			}

			vm.getEsitoIcon = function(esito) {
				if (esito === '1')
					return "fa-clear";
				else if (esito === '2')
					return 'fa-times';
			}

			
			vm.init = function() {

				UserManager.AppVariables().$promise
						.then(function(data) {
							vm.appVariables = data;
						});

				vm.getDisposizioni();
			}

			vm.init();

});

app.controller('dettaglioRecordPagamentiCtrl', 
function ($scope,$mdDialog,utilsSvc, locals) {
	
	$scope.report = locals.report;
	
	$scope.confirmDialog = function() {
        $mdDialog.hide($scope.disposizione);
    }

	$scope.cancelDialog = function() {
    	$mdDialog.cancel();
    }
	
	$scope.largeScreen = function() {
		return utilsSvc.largeScreen();
	}

	$scope.formattaReport=function(report){
		return report.replace(/(?:\r\n|\r|\n)/g, '<br>');
	}    

});