var app = angular.module('golismero-report', [
	'golismero-report-services',
	'ui.chart',
	'templates-app',
	'xeditable',
	'ui.bootstrap',
	'colorpicker.module'
]);
app.config(['dataAccessProvider', function(dataAccessProvider){
    dataAccessProvider.setData(data);
}]);

app.filter('unique', function() {
    return function(input, key) {
        var unique = {};
        var uniqueList = [];
        for(var i = 0; i < input.length; i++){
            if(typeof unique[input[i][key]] == "undefined"){
                unique[input[i][key]] = "";
                uniqueList.push(input[i]);
            }
        }
        return uniqueList;
    };
});
app.value('charting', {
      pieChartOptions: {
        seriesDefaults: {
		  renderer: jQuery.jqplot.PieRenderer,
		  rendererOptions: {
		    showDataLabels: true,							
		    dataLabelPositionFactor: 1.15,
			diameter:150
		  }
		},
		legend: { show:true, location: 's'},
		grid: {drawBorder:false, shadow: false}
      }
    });
app.directive('upload', [function () {
	return {
	 restrict: 'A',
	 link: function (scope, elem, attrs) {
	  var reader = new FileReader();
	  reader.onload = function (e) {
	            scope.general.image = e.target.result;
	            scope.$apply();
	        }

	        elem.on('change', function() {
	         reader.readAsDataURL(elem[0].files[0]);
	        });
	 }
	};
}]);
app.controller('reportController-chart', ['$scope', 'dataAccess','charting', function($scope, $dataAccess, charting){
	$scope.myChartOpts = charting.pieChartOptions;

	$scope.trimArray = function(array, numElements){
		var result = array.slice(0, numElements);

		if(array.length> numElements){
			var o = new Array();
			o[0] = 'Others';
			o[1] = 0;
			for(var i = numElements; i < array.length; i++){
				o[1]+=array[i][1];
			}
			result.push(o);
		}
		return result;
	}

	$scope.chartByType = [$scope.trimArray($dataAccess.getDataChartByType(), 10)];
	$scope.chartByTarget= [$scope.trimArray($dataAccess.getDataChartByTarget(), 10)];
	$scope.chartByCriticality =[$dataAccess.getDataChartByLevel()];

	$scope.$on("changeLevel", function(event, data){
		$scope.chartByCriticality =[$dataAccess.getDataChartByLevel()];
	});
	$scope.$on("changeVulnerabilityType", function(event, data){
		$scope.chartByType =[$scope.trimArray($dataAccess.getDataChartByType(), 10)];
	});
	$scope.$on("deleteVuln", function(event, data){
		$scope.chartByTarget= [$scope.trimArray($dataAccess.getDataChartByTarget(), 10)];
		$scope.chartByType =[$scope.trimArray($dataAccess.getDataChartByType(), 10)];
		$scope.chartByCriticality =[$dataAccess.getDataChartByLevel()];
	});
	
}])

app.controller('reportController', ['$scope', 'dataAccess', 'pdfService', '$filter', '$modal', '$timeout','$window','browser','saveService' , function($scope, $dataAccess, $pdfService, $filter, $modal, $timeout,$window, browser,saveService){

	$scope.logoGolismero = "data:image/png;base64,[encoded data, 6464 characters]";
	$scope.vulnerabilities = $dataAccess.getTargetTechnical();

	targetsTemp =$dataAccess.getAuditScope();
	targetsTemp.unshift('');
	$scope.targets = targetsTemp;
	$scope.targetsResume =$dataAccess.getTargets();

	var arrayVulnerabilities =  $dataAccess.getTargetTechnical().slice(0);//clonamos el array para luego manipularlo
	arrayVulnerabilities.unshift({display_name:''});
    $scope.vulnerabilitiesSelect = arrayVulnerabilities;

    $scope.search = {target_id:'', display_name:''};
    $scope.summary = $dataAccess.getSummary();	
	$scope.vulnsByLevel = $dataAccess.getDataVulnsByLevel();
	$scope.dir = "+";
    $scope.field="level";
    $scope.order = $scope.dir+$scope.field;
    $scope.dataTechnical = $dataAccess.getTargetTechnical();

    $scope.levels = [{value:4, label:'Informational'},
					{value:3, label:'Low'},
					{value:2, label:'Middle'},
					{value:1, label:'High'},
					{value:0, label:'Critical'}];

    $scope.obtainLevel = function(level){
		switch(level){
			case 0: return "critical";
			case 1: return "high";
			case 2: return "middle";
			case 3: return "low";
			case 4: return "informational";
		}
	}

	$scope.saveHTML = function(){
		
		if(browser.value==="safari"){
			var messageInstance = $modal.open({
				templateUrl: 'message.tpl.html',
				controller: MessageController,
				resolve: {
					message: function () {
						return ""
					}
				}
			});

			messageInstance.result.then(function () {
				saveService.saveHTML($window.copyhead, $window.copybody, $dataAccess.getData());
			}, function () {
				//dimiss function
			});
		
		}else{
			saveService.saveHTML($window.copyhead, $window.copybody, $dataAccess.getData());
		}
		
	}
    $scope.sortBy = function(field){
    	if(field == $scope.field){
			if($scope.dir == '+'){
    			$scope.dir = '-';
    		}else{
    			$scope.dir = '+';
    		}
    	}
    	$scope.field= field;
    	$scope.order = $scope.dir+$scope.field;
    }

    $scope.goTo = function(item){
    	$('body,html').stop(true,true).animate({
			scrollTop: $("[data-anchor='technical-"+item+"']").first().offset().top -80
		},1000);
    };

    $scope.obtainTarget = function(id){
		return $dataAccess.getTargetById(id);	    		
	}	

	

	
	$scope.updateLevels = function(item){
		$dataAccess.updateDataVulnsByLevel();
		$scope.$broadcast("changeLevel");
	}

	$scope.updateVulnerabilityType = function(item){
		$dataAccess.updateDataVulnsByType();
		$scope.$broadcast("changeVulnerabilityType");
	}

	

	$scope.deleteItem = function(index, item){

		var modalInstance = $modal.open({
			templateUrl: 'confirm.tpl.html',
			controller: ConfirmDeleteController,
			resolve: {
				vulnerability: function () {
					return item;
				}
			}
		});

		modalInstance.result.then(function (deleteVulnerability) {
			if(deleteVulnerability){
				for(var i= 0; i <$scope.vulnerabilities.length; i++){
					if($scope.vulnerabilities[i].identity==item.identity){
						$scope.vulnerabilities.splice(i, 1);
						break;
					}
				}		
				$scope.updateLevels();
				$scope.updateVulnerabilityType();
				$dataAccess.initDataTarget($scope.vulnerabilities);
				$scope.targetsResume =$dataAccess.getTargets();
				$scope.$broadcast("deleteVuln");
			}
		}, function () {
			//dimiss function
		});

		
	}

	$scope.downloadPdf = function(){

		var modalInstance = $modal.open({
			templateUrl: 'custompdf.tpl.html',
			controller: PdfCustomController,
			size:'lg',
			resolve: {
				data: function(){
					return {
						imgLogo: $scope.logoGolismero,
						auditName: $dataAccess.getSummary().audit_name
					}
				}
			}
		});

		modalInstance.result.then(function (generalInfo) {
			if(generalInfo){
				generalInfo.targetTechnical = $filter('orderBy')($dataAccess.getTargetTechnical(), $scope.order);
				generalInfo.summary.auditScope = $scope.targetsResume;
				generalInfo.summary.summary = $scope.summary;
				generalInfo.summary.stats = $scope.vulnsByLevel;
				$pdfService.createPdf(generalInfo, $("#chartByCriticality").jqplotToImageStr({}),$("#chartByType").jqplotToImageStr({}),$("#chartByTarget").jqplotToImageStr({}));
				
				
			}
		}, function () {
			//dimiss function
		});		
	}


	//controllers modals
	var MessageController = ['$scope','$modalInstance','message',function($scope, $modalInstance, message){
		$scope.message = message;

		$scope.accept = function(){
			$modalInstance.close(true);
		}
		
	}];

	var ConfirmDeleteController = ['$scope','$modalInstance','vulnerability',function($scope, $modalInstance, vulnerability){
		$scope.vulnerability = vulnerability;

		$scope.accept = function(){
			$modalInstance.close(true);
		}
		$scope.close = function(){
			$modalInstance.close(false);
		}
	}];

	//controllers modals
	var PdfCustomController = ['$scope','$modalInstance','data', function($scope, $modalInstance, data){
		
		$scope.general = {
			templateFooter :"%currentPage% of %totalPages%",
			templateHeader: "GoLismero Project - Report",
			enabledHeader:true,
			enabledFooter : true,
			auditName : "Audit name: " + data.auditName,
			image: data.imgLogo,
			orientation: 'portrait',
			summary:{
				showSummary:true,
				showTargets:true,
				showTimes:true,
				showTotals:true
			},
			charts:{
				showCharts:true,
				showVulnCriticality:true,
				showVulnsType:true,
				showVulnsTarget:true
			},
			vulnerabilities:{
				showVulnerabilities:true
			},
			techReport:{
				showTechnicalReport:true
			},
			styles:{
				high:{
			    	color:'#b00700',
			     	description:"Style that sets the text of criticality 'High'"
			    },
			    middle:{
			    	color:'#d7ac00',
			     	description:"Style that sets the text of criticality 'Middle'"
			    },
			    low:{
			    	color:'#019127',
			     	description:"Style that sets the text of criticality 'Low'"
			    },
			    informational:{
			    	color:'#0080ff',
			     	description:"Style that sets the text of criticality 'Informational'"
			    },
			    header: {
			      fontSize: 22,
			      bold: true,
			      margin:[0, 17, 0, 0],
			      description:"Style that sets the title of report"
			    },
			    h2: {
			      fontSize: 18,
			      bold: true,
			      description:"Style that sets the text of the titles of the sections"
			    },
			    h3:{
					fontSize: 12,
					bold:true,
			     	description:"Style that sets the text of the titles within sections"
			    },
			    th:{
					fontSize:10,
					bold:true,
			     	description:"Style that sets the text of headers of tables"
			    },
			    detail: {
			      fontSize: 16,
			      bold: true,
			      description:"Style that sets the text of title of details panel"
			    },			    
			    title:{
			    	fontSize: 14,
			      	bold: true,
			     	description:"Style that sets the text of the vulnerability name of details panel"
			    },
			    critical:{
			    	color:'#b40a9d',
			     	description:"Style that sets the text of criticality 'Critical'"
			    },			   
			    otherText:{
			    	fontSize:10,
			     	description:"Style that sets the other texts (not titles, headers, etc)"
			    },			    
			    headerPage : {
			    	alignment:'right',
			    	margin:10,
			    	description:"Style that sets the text of header"
			    },
			    footerPage: {
			    	alignment:"right",
			    	margin:10,
			    	description:"Style that sets the text of footer"			    	
			    }
			}
		}

		
		

		$scope.generate = function(action){
			$scope.general.action = action;
			var messageInstance = $modal.open({
				templateUrl: 'message.tpl.html',
				controller: MessageController,
				resolve: {
					message: function () {
						return "The process is slow and can block the browser. Please wait for it to finish.";
					}
				}
			});

			messageInstance.result.then(function () {
				$modalInstance.close($scope.general);
			}, function () {
				//dimiss function
			});
		}
		$scope.cancel = function(){
			$modalInstance.dismiss();
		}
	}];

	$timeout(function(){$scope.loaded = true;});
}])
;

