app.controller('tabellaFlussiNonSedaCtrl',
function($scope,$http,$cookies,$window, $location,$timeout, $mdDialog, $q, $routeParams, $mdBottomSheet, $mdMedia, FlussiNonSeda, utilsSvc) {

	var vm=this;
	
	vm.maxItems = 0;
	vm.itemsPerPage = 100;
	vm.selectedIndex=-1;
	vm.records=[];
	vm.filter={
		filterText: '',
		orderField:null
	}
	
	
	vm.setSelected=function(idx) {
		vm.selectedIndex = idx;
	}

	vm.columnWidths=[
			120,  //0
			140,  //1
			120, //2
			380 //3
		];
	
	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',
				'margin-left':'8px',
				'margin-right':'8px'
		};modalitaGenerazione
	}
	
	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()+96)+'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.getFlussiNonSeda();
	}
	

	vm.eliminaElemento=function(idx,event) {
		event.preventDefault();
		event.stopPropagation();		
	
		utilsSvc.showConfirm("Conferma", "Confermi la cancellazione dell'elemento selezionato?")
			.then(function(res){
				FlussiNonSeda.Delete({id:vm.records[idx].id})
					.$promise.then(function(data){
						utilsSvc.showMessage('Eliminazione effettuata');
						vm.getFlussiNonSeda();
					})
			})
	}
	
	vm.nuovoElemento=function(event) {
		FlussiNonSeda.New()
			.$promise.then(function(data){
				data.tipologia="RID";
				vm.records.push(data);
				vm.editElemento(vm.records.length-1,event);
			})
	}

	vm.editElemento = function(idx, ev) {
		$mdDialog.show({
    		targetEvent:ev,
            templateUrl: 'templates/flussoNonSeda.html',
            controller: 'flussoNonSedaCtrl',
            locals: {item: vm.records[idx], descrizione: vm.decodeTipologia(vm.records[idx].tipologia)},
            multiple: true
        }).then(function(res){
        	vm.records[idx] = res;
        	FlussiNonSeda.save({},res).$promise.then(
        		function(res){
        			//vm.records[idx] = res;
        			utilsSvc.showMessage('Salvataggio modifiche effettuato');
        			vm.getFlussiNonSeda();
        		},
        		function(err){
        			utilsSvc.handleHttpError(err);
        		}
			);
        });	

	}
	
	vm.decodeTipologia = function(tipologia) {
		return utilsSvc.decodeTipologia(tipologia);
	}
	
	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];
	          },
	          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 = FlussiNonSeda.List({start: vm.records.length,size:Math.max(vm.records.length+index,vm.itemsPerPage)}).$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.getFlussiNonSeda = function(){
		FlussiNonSeda.Count({filter:vm.filter.filterText}).$promise.then(
			function(data){
				vm.records=[];
				vm.maxItems = data.value;
				vm.infiniteItems.numLoaded_ = 0;
				vm.infiniteItems.toLoad_ = 0;
			
			}
		);
	}
	
	vm.init = function() {
		vm.getFlussiNonSeda();
	}	
	
	vm.init();	
})

.controller("flussoNonSedaCtrl",function($scope, $mdDialog, utilsSvc,locals){
	
	$scope.item = angular.copy(locals.item);
	
	$scope.descrizione = locals.descrizione;
	
	$scope.toUpperCase=function(event) {
		event.key = event.key.toUpperCase(); 
	}
	
	$scope.confirmDialog = function(){
		if ($scope.item.tipologia==null || $scope.item.tipologia=="" ||$scope.item.nomeSupporto==null || $scope.item.nomeSupporto=="") {
			utilsSvc.show("I dati Tipologia e Nome Supporto Flusso sono obbligatori");
			return;
		}
		$mdDialog.hide($scope.item);
	}
	
	$scope.cancelDialog=function(){
		$mdDialog.cancel();
	}
	
})

;