
var chartSeries = [];
var chartColors = ["red", "green", "blue", "black", "orange", "#808080", "#06230b"]
var chartTitle='';
var titleTooltip= "";
var yAxisTitle = "";
var uuid="";
var chart=null;
isProduction=false;


function Request() {
    var request = {
        url: "",
        parameters: {},
        Type: ""
    };
}
Highcharts.setOptions({
    global: {
        useUTC: true
    }
});
$(function() {
    var chartData = [];


    var response = [{
        "component": 'CPU',
        "componentPath": 'CPU'
    }, {
        "component": 'Memory',
        "componentPath": 'Memory'
    }, {
        "component": 'Disk',
        "componentPath": 'Disk'
    }, {
        "component": 'DF',
        "componentPath": 'DF'
    }]
    $('#ddlComponent').append(new Option('-- Select --', 0));
    $.each(response, function(i, item) {
        $('#ddlComponent').append(new Option(item.component, item.componentPath));
    });

});



function Renderchart(series) {
    chart = Highcharts.chart('graph-chart-container', {
        chart: {
            type: 'spline',
            zoomType: 'xy',
            //backgroundColor: "#9e9e9e",
            animation: Highcharts.svg, // don't animate in old IE
            marginRight: 10,
        },
        credits:{
            enabled:true,
            text:'pilotphotonics.com',
            href:"http://www.pilotphotonics.com"
        },
        title: {
            text: '<span title="'+titleTooltip+'">' + '' + ' Analytics'+'</span>',
            style: {
                "color": "black",
                "fontSize": "20px",
                fontWeight: 'bold'
            },
			useHTML:true
        },
        xAxis: {
            type: 'datetime',
            dateTimeLabelFormats: {
                day: "%e. %b",
                month: "%b '%y",
                year: "%Y"
            },
            tickInterval: 1,
            title: {
                text: 'Time',
                style: {
                    "color": "black",
                    "fontSize": "15px",
                    fontWeight: 'bold'
                },
            },

        },
        yAxis: {
            // max: 100,
            // min: 0,
            title: {
                text: yAxisTitle,
                style: {
                    "color": "black",
                    "fontSize": "15px",
                    fontWeight: 'bold'
                },
            },
            gridLineWidth: 0,
            plotLines: [{
                value: 0,
                width: 1,
                color: '#808080'
            }]
        },
        legend: {
            enabled: true,

        },
        colors: ["red", "green", "blue", "black", "orange", "#808080", "#06230b"],
        exporting: {
            enabled: true
        },
        plotOptions: {
            series: {
                showCheckbox: false,
                marker: {
                    enabled: false
                },
                events: {
                    checkboxClick: function(event) {
                        if (event.checked) {
                            this.show();
                            this.legendSymbol.hide();
                        } else {
                            this.hide();
                            this.legendSymbol.hide();
                        }
                    },
                    click: function (event) {
                            writeStatusLogData(this.name,event.point.x,event.point.y);
                    }
                }
            }
        },

        series: series,

        responsive: {
            rules: [{
                condition: {
                    maxWidth: 500
                },
                chartOptions: {
                    legend: {
                        layout: 'horizontal',
                        align: 'center',
                        verticalAlign: 'bottom'
                    }
                }
            }]
        }

    });
	
	 $('#plain').click(function() {
     chart.update({
			 chart: {
				 inverted: false,
				 polar: false
			 },
		 subtitle: {
			text: 'Plain'
			}
		});
     });


}



function PrepareData(data) {
    chartData = data;
	chartSeries=[];
	for(var prop in data) {
        if (prop == "ccm" || prop == "deviceList")
            continue;
		var device = ConvertToSeriesData(data[prop],prop);
		for(var i in device)
		{
			if(device[i].data.length>0)
				chartSeries.push(device[i]);
		}
	}
	
	//chartSeries = ConvertToSeriesData(chartData);
    chartSeries = UpdateColors(chartSeries)
    //StartChart(chartSeries);
    if(chartSeries.length == 0){
        isGraphThere = false;
        if(data["ccm"] == 1){
            if(!isTimeOutFunction)
            swal("Warning", "CCM is running, graph will be updated soon", "warning");
            if(isTimeChartCalled == false){
                isTimeChartCalled = true;
                setTimeout(function(){
	            let selectedMetric = $("input[name='chartDevice']:checked").val(); 
                let scale = $("input[name='chartSclae']:checked").val();
                if(isGraphThere == false){
        		InitializeChart(g_deviceName, selectedMetric, scale);
                isTimeOutFunction = true;
                }
                    isTimeChartCalled = false;
                }, 30000);
            }
        }
        else if(data["ccm"] == 0)
            swal("Error", "CCM socket not active", "error");
        else {
            swal("Error", "CCM socket not active", "error");
        }
        try{
            chart.destroy()
        }
        catch{

        }

        return ;
    }
	else {
        $("#graph-water-mark").hide();
		// console.log("Data")
	}
    
    // if(chart!=null){
    //     var len=chart.series.length;
    //     for (var i = 0; i < len; i++) {
    //         chart.series[0].remove();
    //     }

    //     for (var i = 0; i < chartSeries.length; i++) {
    //         chart.addSeries(chartSeries[i], false);
    //     }
    //     chart.redraw();
    // }
    // else
    
    isGraphThere = true;
    Renderchart(chartSeries);

}

function ConvertToSeriesData(Data,Name) {
	var seriesNames = Data[1].columns;
    var seriesData = [{
        name: seriesNames[0],
        selected: false,
        data: []
    },{
        name: seriesNames[1],
        selected: false,
        data: []
    },{
        name: seriesNames[2],
        selected: false,
        data: []
    },];

    seriesData =[];
    $.each(seriesNames, function(index, item) {
        var seriesItem = {
            name: item,
            selected: false,
            data: []
        }
        seriesData.push(seriesItem);
    });

    var config = Data[0];
    var startTime = config.epoch_range[0];
    var endTime = config.epoch_range[1];
    var numInterval = config.epoch_range[2];
    var timeDiff = numInterval;// / 60;
    Data.shift();
	Data.shift();

    var epochValue = startTime;
    
    $.each(Data, function(index, item) {
        var d = new Date(0);
        d.setUTCSeconds(epochValue);
        
        $.each(item.row, function(rowIndex, rowItem) {
            seriesData[rowIndex].data.push([Date.UTC(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds()), rowItem]);
        });

		 epochValue = epochValue + timeDiff;
    });

    return (seriesData);
}

function UpdateColors(data) {
    for (var i = 0; i < data.length; i++) {
        data[i].color = chartColors[i];
    }
    return data;
}

function CallPythonServiceChart(request) {
    $("#graph-water-mark").show();
    $("#graph-chart-container").hide();
	request.parameters.uuid=uuid;
    $.ajax({
        type: "Get",
        url: request.url,
        contentType: 'application/json',
        dataType: 'json',
        headers: { 'Access-Control-Allow-Origin': '*' },
        data: request.parameters,
        success: function (response) {
            // $("#graph-water-mark").hide();
            $("#graph-chart-container").show();
			
			PrepareData(response);
			
        },
        error: function (ex) {		
			// PrepareData(response);
            swal("Error", "Backend Error", "error");
            if(!isProduction){
				//console.log(ex);
			}
        }
    });
}

function InitializeChart(deviceName,metricType,scale)
{
	chartTitle = "Hard Coded";
	yAxisTitle = metricType == 'D' ? 'used %' : deviceName;
	titleTooltip = 'Selected Metric: ' + deviceName;
	
	var request = new Request();
	request.url ="../cgi/cgi_RRD_Manager.py";
	request.parameters={"requestType":metricType,"device":deviceName,"scale":scale,"NumHorizontal_points_in_graph":10};
	CallPythonServiceChart(request);
}
$(window).bind("load", function() {    
	InitializeChart(g_deviceName,'T','mins');
});

function writeStatusLogData(name,x,y){
    $.ajax({
                type: "Get",
                url: '../cgi/cgi_StatusLogs.py',
                contentType: 'application/json',
                dataType: 'json',
                headers: { 'Access-Control-Allow-Origin': '*' },
                data: {name:name,x_param:x,y_param:y},
                success: function (response) {
                    alert(response.description);
                },
                error: function (ex) {
                    $("#test").html(ex.responseText)
                }
    }); 
}
