app.controller('ordinantiCtrl',
	
function ($scope,$http,$cookies,$window, $location,$timeout, $mdDialog, $q, $routeParams, $mdBottomSheet, $mdMedia, userService, utilsSvc, Ordinanti, UserManager) {
	
	var vm=this;
	
	vm.idOrdinante = $routeParams.idOrdinante;
	vm.maxItems = 0;
	vm.maxContiItems =  0;
	vm.itemsPerPage = 100;
	vm.selectedIndex=-1;
	vm.records=[];
	vm.filter={
		orderField:null
	};
	
	vm.appVariables = {};
	
	vm.setSelected=function(idx) {
		vm.selectedIndex = idx;
	}
	
	vm.columnWidths=[
			250,  //0
			115,
			115,
			190,
			250,
			80,
			150,
			80
		];

	UserManager.AppVariables().$promise.then(function(data) {
		vm.appVariables = data;
	});
	
	vm.getGridItemHeight = function() {
		return utilsSvc.getGridHeight();
	}
	
	vm.stampaOrdinanti = function() {
		utilsSvc.showForever('Generazione in corso...');
		Ordinanti.Print({},$scope.filter).$promise.then(function(data){
				utilsSvc.downloadFile('application/pdf',data.response,'Ordinanti.pdf');
				utilsSvc.cancelMessage();
			}).catch(function(err){
				if (err.status==404) {
					utilsSvc.cancelMessage();
					utilsSvc.showMessage('Nessun ordinante estratto');
				} else 
					utilsSvc.handleHttpError(err);
			});		;

	}
	
	vm.showCommands = function(distinta,index,$event) {
		vm.selectedIndex = index;
	    $mdBottomSheet.show({
	      templateUrl: 'templates/bottom-sheet-template.html',
	      controller: 'comandiOrdinantiCtrl',
	      locals:{idx: index, appVariables: vm.appVariables},
	      targetEvent: $event
	    }).then(function(selectedCommand) {
	      vm.executeCommand(selectedCommand.cmdIndex, selectedCommand.recordIdx, $event);
	    }, 
    	function(){}
	    );
	}
	
	
	vm.executeCommand = function(id,idx, $event) {
		$scope.filterChiamante = userService.getFiltroIncassiSDD();
		$scope.filterChiamante.tipoChiamata = "Destinatari";
		userService.setFiltroIncassiSDD($scope.filterChiamante);
		switch(id) {
			case 0: vm.editDestinatario(vm.records[idx], $event); break;
			case 1: vm.apriDestinatari(vm.records[idx], $event); break;
			case 2: vm.apriDelegheSeda(vm.records[idx], $event); break;
		}
	}

	vm.nuovoOrdinante = function(ev){
		Ordinanti.New().$promise.then(function(res){
			vm.records.push(res);
			vm.editDestinatario(vm.records[vm.records.length-1], event);
		});
	}

	vm.editDestinatario=function(ordinante, event) {
		$mdDialog.show({
            templateUrl: 'templates/ordinante.html',
            controller: 'ordinanteCtrl',
            targetEvent: event,
            locals: ordinante,
            multiple: true
        }).then(function(ordinante){
        	Ordinanti.save({}, ordinante).$promise.then(function(res){
        		utilsSvc.showMessage('Salvataggio modifiche effettuato');
        		vm.getOrdinanti();
        	},
        	function(){
        		vm.getOrdinanti();
        	})
        })
	}

	vm.apriDestinatari=function(ordinante, event) {
		$mdDialog.show({
            templateUrl: 'templates/destinatari.html',
            controller: 'destinatariCtrl',
            locals: {ordinante:ordinante, ordinanti: vm.records},
            multiple: true
        });
	}
	
	vm.apriDelegheSeda=function(ordinante, event) {
    	$mdDialog.show({
            templateUrl: 'templates/delegheSeda.html',
            controller: 'delegheSedaCtrl',
            targetEvent: event,
            locals: {idOrdinante:ordinante.idordinante, tipo: ''},
            multiple: true
        })	
	}
	
	vm.getListHeight = function() {
		containerHeight = ($window.innerHeight - $('#container').position().top - $('#view').position().top);
		  return {'height':  containerHeight + 'px'};
	};
	$window.addEventListener('resize', onResize);
	function onResize() {
	  $scope.$digest();
	}
	$scope.$on('$destroy', function() {
	  $window.removeEventListener('resize', onResize);
	});
	
	
	vm.getColumnWidth = //	              }
		//        this.lastStartIdx = index;
		function(idx) {
		return {
				'width': vm.columnWidths[idx] + 'px', 
				'min-width':vm.columnWidths[idx] + 'px',
				'max-width':vm.columnWidths[idx] + 'px',
				'margin-left':'8px',
				'margin-right':'8px',
				'text-overflow': 'ellipsis',
				'overflow': 'hidden',
			    'white-space':'nowrap'
			    	
		};
	}
	
	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.getOrdinanti();
	}


	
	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) {
	        			  this.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;
	              
        		  this.listPromise = Ordinanti.List({idOrdinante: vm.idOrdinante, filter:vm.filter.filterText, start: vm.records.length,size:Math.max(vm.records.length+index,vm.itemsPerPage),orderBy:vm.filter.orderField}).$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;
			              			},
			              			function(error) {
			              				vm.infiniteItems.loading_ = false;
			              				vm.infiniteItems.toLoad_=0;
			              				utilsSvc.handleHttpError(error);
			              			}
			              	)
            	}
          }
	}	


	vm.contiInfiniteItems = {
	          numLoaded_: 0,
	          toLoad_: 0,
	          loading_:false,
	          lastStartIdx:-1,
	          listPromise:null,
	          canceler: $q.defer(),
	          // Required.
	          getItemAtIndex: function(index) {
	        	  if (vm.maxContiItems==0 ||  index>vm.maxContiItems)
	        		  return null;
	        	  if (!vm.contiInfiniteItems.loading_)
	        		  if (index > vm.recordsConti.length) {
	        			  this.fetchMoreItems_(index);
	        			  return null;
	        		  }
	            return vm.recordsConti [index];
	          },
	          // Required.
	          // For infinite scroll behavior, we always return a slightly
				// higher
	          // number than the previously loaded items.
	          getLength: function() {
      		  return vm.maxContiItems;
	        	  
	          },
	          fetchMoreItems_: function(index) {
	            if (this.toLoad_ < index) {
	              this.toLoad_ += vm.itemsPerPage;
	              utilsSvc.showWaitMessage('Ricerca in corso...');
	              vm.contiInfiniteItems.loading_ = true;
	              
	              this.listPromise = ContiDestinatario.List({start: vm.recordsConti.length,size:Math.max(vm.recordsConti.length+index,vm.itemsPerPage),orderBy:vm.filter.orderField}).$promise;
		              
	              var mod=this;
		              this.listPromise.then(
			              			function(data){
			              				vm.contiInfiniteItems.loading_ = false;
			              				vm.contiInfiniteItems.toLoad_=0;
			              				utilsSvc.cancelWaitMessage();
			              				vm.records = vm.recordsConti.concat(data);
			              				mod.numLoaded_ = vm.recordsConti.length;
			              				mod.lastStartIdx = vm.recordsConti.length;
			              			},
			              			function(error) {
			              				vm.contiInfiniteItems.loading_ = false;
			              				vm.contiInfiniteItems.toLoad_=0;
			              				utilsSvc.handleHttpError(error);
			              			}
			              	)
          	}
        }
	}	
	
	vm.eliminaOrdinante = function(ndx, event) {
		utilsSvc.showConfirm("Confermi la cancellazione dell'ordinante?", "Conferma", event)
			.then(function(res){
				Ordinanti.Delete({id: vm.records[ndx].idordinante}).$promise.then(function(data){
					utilsSvc.showMessage("Eliminazione effettuata");
					vm.getOrdinanti();
				},
      			function(error) {
      				utilsSvc.handleHttpError(error);
      			});
			});		
	}
	
	vm.getOrdinanti = function(){
		Ordinanti.Count({idOrdinante: vm.idOrdinante, filter:vm.filter.filterText}).$promise.then(
					function(data){
						vm.records=[];
						vm.maxItems = data.value;
						vm.infiniteItems.numLoaded_ = 0;
						vm.infiniteItems.toLoad_ = 0;
					
					}
				);
	}
	
	vm.getContiDestinaraio = function(idDestinatario){
		Ordinanti.Count({idDestintario: idDestinatario}).$promise.then(
					function(data){
						vm.records=[];
						vm.maxContiItems = data.value;
						vm.contiInfiniteItems.numLoaded_ = 0;
						vm.contiInfiniteItems.toLoad_ = 0;
					
					}
				);
	}
	
	
	vm.init = function() {
		
		
		vm.getOrdinanti();
	}	
	
	
	vm.init();

}
)

.controller('comandiOrdinantiCtrl', function($scope, $mdBottomSheet, locals) {

	$scope.title = 'Comandi';
	
	$scope.items = [
		{ id:0,  name: "Modifica", icon: 'fa-pencil',visible: true },
	    { id:1,  name: "Destinatari", icon: 'fa-users',visible: true },
	    { id:2,  name: "Deleghe SEDA", icon: 'fa-refresh', visible: true }
		];
	
	if (locals.appVariables.profiloLocale=="TR" && !locals.appVariables.abilitaAccessoAnagrafica)
		$scope.items[1].visible = false;
	
	$scope.listItemClick = function($index, $event) {
	    var clickedItem = $scope.items[$index];
	    var result = {cmdIndex: $index, recordIdx: locals.idx, event:$event}
	    $mdBottomSheet.hide(result);
	  };
	  
	  $scope.dismissBottomSheet = function() {
		  $mdBottomSheet.cancel();
	  }
})
.controller('ordinanteCtrl', function($scope,$mdDialog,utilsSvc,locals) {
	$scope.ordinante = angular.copy(locals);
	
	$scope.controllaCF=function(){
		if (!utilsSvc.controllaCFoPiva($scope.ordinante.codiceFiscale))
			utilsSvc.showMessage("Codice fiscale / partita IVA non valido");
	}
	
	$scope.confirmDialog = function() {
		if ($scope.checkDati()) {
			if ($scope.ordinante.conto!=null)
				$scope.ordinante.conto = $scope.ordinante.conto.toUpperCase();
			$mdDialog.hide($scope.ordinante);
		}
	}
	
	$scope.cancelDialog = function() {
		$mdDialog.cancel();
	}
	
	$scope.checkDigit=function(event, len){
		if (event.key=="Backspace" || event.key=="ArrowLeft" || event.key=="ArrowRight" || event.key=="Tab")
			return;
		if ("0123456789".indexOf(event.key)==-1 || event.target.value.length>=len)
			event.preventDefault();
	}
		
	
	$scope.checkDati = function() {
		if ($scope.ordinante.ordinante==null || $scope.ordinante.ordinante=='' ){
			utilsSvc.showMessage("Inserire la denominazione dell'ordinante");
			return false;
		}		
		if ($scope.ordinante.codiceFiscale==null || $scope.ordinante.codiceFiscale=='' ){
			utilsSvc.showMessage("Inserire il codice fiscale / partita IVA dell'ordinante");
			return false;
		}	
		if ($scope.ordinante.codiceSia==null || $scope.ordinante.codiceSia=='' ){
			utilsSvc.showMessage("Inserire il codice SIA dell'ordinante");
			return false;
		}	
		return true;
	}
	
}
)

;	  
	