app.controller('logSicuraSchedulerCtrl',
	
function ($scope,$http,$cookies,$window, $location,$timeout, $mdDialog, $q, utilsSvc, LogSicuraScheduler) {
	
	var vm=this;

	
	vm.maxItems = 0;
	vm.itemsPerPage = 100;
	vm.records=[];
	vm.inputFile='';
	vm.selectedIndex = -1;
	vm.logDetails = "";
	
	vm.columnWidths=[
			150,  //0
			350,  //1
			250,  //2
			380,  //3
			380   //4
		];

	vm.getListHeight = function() {
		containerHeight = (($window.innerHeight - $('#container').position().top - $('#view').position().top))*0.6;
		  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);
	});

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

	
	vm.onlyFilename = function(filepath) {
		if (!filepath || filepath=="")
			return "";
		var term='\\';
		if (filepath.indexOf('/')>0)
			term='/';
		if (filepath.indexOf(term)>=0)
			return filepath.substr(filepath.lastIndexOf(term)+1);
		else
			return filepath;
	}
	
	
	vm.getColumnWidth = function(idx) {
		return {
				'width': vm.columnWidths[idx] + 'px', 
				'min-width':vm.columnWidths[idx] + 'px',
				'margin-left':'8px',
				'margin-right':'8px',
				'text-overflow': 'ellipsis',
				'overflow': 'hidden',
			    'white-space':'nowrap'
		};
	}
	
	vm.getLogDetail = function(idx) {
		vm.selectedIndex = idx;
		LogSicuraScheduler.LogDetail({id:vm.records[idx].id})
		.$promise.then(function(data){
			vm.logDetails = data;
		});
		
	}
	
	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.orderField!=field)
			vm.orderField = field;
		else
			vm.orderField = "-" +field;
		
		vm.getLog();
	}

	
	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 = LogSicuraScheduler.List({start: vm.records.length,size:Math.max(vm.records.length+index,vm.itemsPerPage), inputFile: vm.inputFile, orderBy:vm.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;
		              				if (vm.selectedIndex==-1) {
		              					vm.selectedIndex = 0;
		              					vm.getLogDetail(0);
		              				}
		              			},
		              			function(error) {
		              				vm.infiniteItems.loading_ = false;
		              				vm.infiniteItems.toLoad_=0;
		              				utilsSvc.handleHttpError(error);
		              			}
		              	);
	            }
	         }
	}	

	

	vm.getLog = function(){
		LogSicuraScheduler.Count({inputFile: vm.inputFile},
				function(data){
					vm.records=[];
					vm.maxItems = data.value;
					vm.infiniteItems.numLoaded_ = 0;
					vm.infiniteItems.toLoad_ = 0;
				}
			);
	}
	
	vm.getLog();
	
});