/**
 Description: Controller for CPU Utilization Controller
 Copyright (c) 2016 by Cisco Systems, Inc.
 All rights reserved.
 */

app.controller('CpuAndMemoryUtilizationCtrl', ['$scope','$interval','DashletService','gridCrudService', '$filter','requestRoutingService','dashletReloadTime',
              function ($scope, $interval,dashletService,gridCrudService,$filter,requestRoutingService,dashletReloadTime) {
	var translate = $filter("translate");
	//CPU Util array with 2 empty val initially
	var arrCPUUtil=new Array();
	arrCPUUtil.push(" ");
	arrCPUUtil.push(" ");
	//IO Memory Util array with 2 empty val initially
	var arrIOMemoryUtil=new Array();
	arrIOMemoryUtil.push(" ");
	arrIOMemoryUtil.push(" ");
	//Processor Memory Util array with 2 empty val initially
	var arrProcessorMemoryUtil=new Array();
	arrProcessorMemoryUtil.push(" ");
	arrProcessorMemoryUtil.push(" ");
	//Device Time array with 2 empty val initially
	var arrDeviceTime=new Array();
	arrDeviceTime.push(" ");
	arrDeviceTime.push(" ");
	
	//Refresh Memory and CPU Util for every 60 seconds
	var cpuMemUtilFetchLoop = $interval(function(){
		if(angular.element(".memoryCPUContainer").length > 0){
			loadCPUChart();
		} else {
			$interval.cancel(cpuMemUtilFetchLoop);
		}
	}, dashletReloadTime);
	//for initial load
	loadCPUChart();
	
//CPU UTILIZATION  
	function loadCPUChart(){ 		
		var strCLIOutput = deviceCommunicator.getExecCmdOutput("show clock");
		var arrTime=strCLIOutput.split(":"),
	    deviceTime=arrTime[0]+":"+arrTime[1];
		arrDeviceTime.push(deviceTime);
		//for displaying last 3 values
		if(arrDeviceTime.length>3){
			arrDeviceTime.shift();
		}
		
		var processCPU =requestRoutingService.getShowCmdOutput("show processes cpu sorted","cpuUtilization");
	    var fiveSecCPUDetails=processCPU.entry.fiveSec,
		arrFiveSecCPU=fiveSecCPUDetails.split("/"),
		fiveSecCPU=arrFiveSecCPU[0].substring(0,arrFiveSecCPU[0].length-1),
		cpuInterrupt=arrFiveSecCPU[1].substring(0,arrFiveSecCPU[1].length-2),
		oneMinCPU=processCPU.entry.oneMin,
		oneMinCPU=oneMinCPU.substring(0,oneMinCPU.length-2);
	  	arrCPUUtil.push(oneMinCPU);
		if(arrCPUUtil.length>3){
			arrCPUUtil.shift();
		}
		fiveMinCPU=processCPU.entry.fiveMin,
	    fiveMinCPU=fiveMinCPU.substring(0,fiveMinCPU.length-1);  
	    
		//Removing this content from displaying on UI as per the selecon req, and commenting this code if the same required in future
		/*var items =[{
				"timeDetails":translate("db_cpuutil_fivesec"),
				"percentage": ""+fiveSecCPU+""
			},{
				"timeDetails":translate("db_cpuutil_interrupt"),
				"percentage": ""+cpuInterrupt+""
			},{
				"timeDetails":translate("db_cpuutil_onemin"),
				"percentage": ""+oneMinCPU+""
			},{
				"timeDetails":translate("db_cpuutil_fivemin"),
				"percentage": ""+fiveMinCPU+""
		}];     
		$scope.cpuData = new kendo.data.ObservableArray(items)
		$scope.cpuGridDataSource = new kendo.data.DataSource({
			data : $scope.cpuData
		});	
		$scope.cpuGridOptions =
	    {   editable: false,
	        sortable: false,
	        scrollable:false,
	        selectable: false,
	        columns: [
	            {
	                field: "timeDetails", 
	                title : translate("db_cpuutil_time")
	            },
	            {
	                field: "percentage", 
	                title : translate("db_cpuutil_cpuper")
	            }
	        ]
	    };*/
		
	    $scope.cpuUtilizationOptions={
	    		legend: {
	                position: "bottom"
	            },
	            seriesColors: ["#725D87"],
	            seriesDefaults: {
	                type: "column",
	                "overlay" : {
	                    "gradient" : "none"
	                }
	            },
	            series: [{
	                name: "CPU %",
	                data: arrCPUUtil,
	                
	                interruptData: cpuInterrupt,
	                interruptName:translate("db_cpuutil_interrupt"),
	                
	                fiveMinData: fiveMinCPU,
	                fiveMinName:translate("db_cpuutil_fivemin"),
	            }],
	            valueAxis: {
	                labels: {
	                    format: "{0}%"
	                },
	                line: {
	                    visible: false
	                },
	                axisCrossingValue: 0
	            },
	            chartArea: {
	                height: 240
	            },
	            categoryAxis: {
	                categories: arrDeviceTime,	                
	            },
	            tooltip: {
	                visible: true,
	                format: "{0}%",
	                template: "#= series.name #: #= value #<br>#=series.interruptName #: #= series.interruptData #<br>#=series.fiveMinName #: #= series.fiveMinData #"
	            }
	        };  
	      loadMemoryChart(arrDeviceTime);
		}		

 //MEMORY UTILIZATION  
	function loadMemoryChart(arrDeviceTime){	
		var ioMemory =requestRoutingService.getShowCmdOutput("show processes memory sorted","memoryIOUtilization");
	    var totalIOMemory=ioMemory.entry.IOTotal,
	    usedIOMemory=ioMemory.entry.IOUsed,
	    freeIOMemory=ioMemory.entry.IOFree,
	    percentIoMemory=(parseFloat(usedIOMemory)/parseFloat(totalIOMemory))*100;
	    arrIOMemoryUtil.push(Math.round(percentIoMemory));
		if(arrIOMemoryUtil.length>3){
			arrIOMemoryUtil.shift();
		}
	    
	    var processorMemory =requestRoutingService.getShowCmdOutput("show processes memory sorted","memoryUtilization");
	    var totalProcessorMemory=processorMemory.entry.processorTotal,
	    usedProcessorMemory=processorMemory.entry.processorUsed,
	    freeProcessorMemory=processorMemory.entry.processorFree,
	    percentProcessorMemory=(parseFloat(usedProcessorMemory)/parseFloat(totalProcessorMemory))*100;
	    arrProcessorMemoryUtil.push(Math.round(percentProcessorMemory));
		if(arrProcessorMemoryUtil.length>3){
			arrProcessorMemoryUtil.shift();
		}	
		//Removing this content as per the selecon req, and commenting this code if the same required in future
		/*var memoryItems =[{
				"memoryDetails":translate("db_memory_util_pptotal"),
				"size": ""+totalProcessorMemory+""
			},{
				"memoryDetails":translate("db_memory_util_ppused"),
				"size": ""+usedProcessorMemory+""
			},{
				"memoryDetails":translate("db_memory_util_ppfree"),
				"size": ""+freeProcessorMemory+""
			},{
				"memoryDetails":translate("db_memory_util_iototal"), 
				"size": ""+totalIOMemory+""
		   },{
				"memoryDetails":translate("db_memory_util_ioused"), 
				"size": ""+usedIOMemory+""
			},{
				"memoryDetails":translate("db_memory_util_iofree"), 
				"size": ""+freeIOMemory+""
			}];     
		$scope.memoryData = new kendo.data.ObservableArray(memoryItems)
		$scope.memoryGridDataSource = new kendo.data.DataSource({
			data : $scope.memoryData
		});	
		$scope.memoryGridOptions =
	    {   editable: false,
	        sortable: false,
	        scrollable:false,
	        selectable: false,
	        columns: [
	            {
	                field: "memoryDetails", 
	                title : translate("db_memory_util_details")
	                
	            },
	            {
	                field: "size", 
	                title : translate("db_memory_util_size") 
	            }
	        ]
	    };*/
		
			
        $scope.memoryUtilizationOptions={
    		legend: {
                position: "bottom"
            },
            seriesColors: ["#9EC654","#0096D6"],
            seriesDefaults: {
                type: "column",
                "overlay" : {
                    "gradient" : "none"
                }
            },
            series: [{
                name:translate("db_memory_util_pppercentage"),
                data: arrProcessorMemoryUtil,
                
                totalMemoryName:translate("db_memory_util_pptotal"),
                totalMemory:bytesToSize(totalProcessorMemory),
                
                usedMemoryName:translate("db_memory_util_ppused"),
                usedMemory:bytesToSize(usedProcessorMemory),
                
                freeMemoryName:translate("db_memory_util_ppfree"),
                freeMemory:bytesToSize(freeProcessorMemory)
            },{
                name:translate("db_memory_util_iopercentage"),
                data: arrIOMemoryUtil,
               
                totalMemoryName:translate("db_memory_util_iototal"),
                totalMemory:bytesToSize(totalIOMemory),
                
                usedMemoryName:translate("db_memory_util_ioused"),
                usedMemory:bytesToSize(usedIOMemory),
                
                freeMemoryName:translate("db_memory_util_iofree"),
                freeMemory:bytesToSize(freeIOMemory)
            }],
            valueAxis: {
                labels: {
                    format: "{0}%"
                },
                line: {
                    visible: false
                },
                axisCrossingValue: 0
            },
            chartArea: {
                height: 240
            },
            categoryAxis: {
                categories: arrDeviceTime,
                
            },
            tooltip: {
                visible: true,
                format: "{0}%",               
                template: "#=series.name #: #= value #<br>#=series.totalMemoryName #: #= series.totalMemory #<br>#=series.usedMemoryName #: #= series.usedMemory #<br>#=series.freeMemoryName #: #= series.freeMemory #"
            }
        }; 
        
        //converting bytes to MB
        function bytesToSize(bytes) {
        	   var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
        	   if (bytes == 0) return '0 Byte';
        	   var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
        	   return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
        };
	}
   	    
}]);

