app.controller('tabellaFirmeDistinteCtrl',
function($scope,$http,$cookies,$window, $location,$timeout, $mdDialog, $q, $routeParams, $mdBottomSheet, $mdMedia, Firme, 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'};
	};
	vm.getGridItemHeight = function() {
		return utilsSvc.getGridWithButtonHeight();
	}
	$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'
		};
	}
	
	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.getFirme();
	}
	

	vm.cancellaFirma=function(idx,event) {
		event.preventDefault();
		event.stopPropagation();		
		utilsSvc.showConfirm("Conferma", "Confermi la cancellazione dell'elemento selezionato?")
			.then(function(res){
				Firme.Delete({id:vm.records[idx].id})
					.$promise.then(function(data){
						utilsSvc.showMessage("Cancellazione effettuata");
						vm.getFirme();
					})
			})
	}
	
	vm.nuovaFirma=function(event) {
		Firme.New()
			.$promise.then(function(data){
				vm.records.push(data);
				vm.editFirma(vm.records.length-1,event);
			})
	}

	vm.editFirma = function(idx, ev) {
		$mdDialog.show({
    		targetEvent:ev,
            templateUrl: 'templates/firma.html',
            controller: 'firmaCtrl',
            locals: {firma: vm.records[idx], descrizione: vm.decodeTipologia(vm.records[idx].tipologia)},
            multiple: true
        }).then(function(res){
        	vm.records[idx] = res;
        	Firme.save({},res).$promise.then(
        		function(res){
        			vm.records[idx] = res;
        			utilsSvc.showMessage('Salvataggio modifiche effettuato');
        			vm.getFirme();
        		},
        		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 = Firme.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.getFirme = function(){
		Firme.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.getFirme();
	}	
	
	vm.init();	
})

.controller("firmaCtrl",function($scope, $mdDialog,utilsSvc,locals){
	
	$scope.firma = angular.copy(locals.firma);
	
	$scope.descrizione = locals.descrizione;
	
	$scope.confirmDialog = function(){
		if ($scope.firma.tipologia==null ||$scope.firma.tipologia.trim()=='' || $scope.firma.prefissoFlussoInput==null || $scope.firma.prefissoFlussoInput.trim()=='') {
			utilsSvc.show('I dati Tipologia e Prefisso Flusso sono obbligatori');
			return;
		}
		$mdDialog.hide($scope.firma);
	}
	
	$scope.cancelDialog=function(){
		$mdDialog.cancel();
	}
	
})

;