﻿/*
    ChartAndGridPanel
*/

Veeam.ChartAndGridPanel = Ext.extend(Ext.BoxComponent, {
    id: 'live-chart',
    initComponent: function(){

        this.isLog =  Ext.state.Manager.get('dashboard-chart-panel-isLog') || false;
        Veeam.ChartAndGridPanel.superclass.initComponent.apply( this );

        this.addListener('resize', this.resizeHandler, this, { buffer: 50 } );

    },

    destroy: function() {
        Veeam.ChartAndGridPanel.superclass.destroy.apply(this, arguments);
    },
    
    render: function() {
        Veeam.ChartAndGridPanel.superclass.render.apply(this, arguments);
        this.loadImage();
    }, 
    
    selectScaleHandler : function(e, t, o) {
        this.isLog = o.isLog;
        Ext.state.Manager.set('dashboard-chart-panel-isLog', this.isLog);
        this.loadImage();
    }, 
    
    loadImage: function() {



        var params = Ext.apply({
            imageKey: this.initialConfig.imageKey ,
            isLog: this.isLog,
            json: true
        }, this.initialConfig.imageConfig );


        Ext.Ajax.request({
            url: 'ChartDataHandler.ashx',
            success: function(response, opt) {
                var obj = Ext.decode(response.responseText);
                this.initializeLiveChart(obj);

            },
            failure: function(response, opt){
                return Veeam.Msg.error({ msg: response.responseText } );
            },
            params: params,
            method: 'GET',
            scope: this
        });

    },

    initializeLiveChart: function(config){

        var logFormatter = function() {
            return  Highcharts.numberFormat( Math.pow(10, this.value) );
        };


        var tooltipFormatter = config.yAxis.log_scale ?
                function() { return this.y == 0 ? 0 : Highcharts.numberFormat(Math.pow(10, this.y), 3); } :
                function() { return Highcharts.numberFormat(this.y, 3); }


        var xAxisFormatter = function(){
            var dt = new Date(this.value);
            var c = config;
            return dt.format( c.weekly ? Veeam.Defaults.dateFormat : Veeam.Defaults.timeFormat );

        };
        var options = Ext.apply( config || {}, {
             chart: {
                 renderTo: 'live-chart',
                 defaultSeriesType: 'spline',
                 showAxes: true,
                 animation: false
             },
             title : Ext.apply({}, config.title , {
                 text: ''
             }),
             xAxis: Ext.apply({}, config.xAxis, {
                 type: 'datetime',

                 labels: { style: { color: '#333333'}, formatter : xAxisFormatter }
             }),
             yAxis: Ext.apply({}, config.yAxis, {
                 minorGridLineWidth: 1,
                 gridLineWidth: 1,
                 alternateGridColor: null,
                 labels: {
                     style: { color: '#333333' },
                     formatter: ( config.yAxis.log_scale == true  ? logFormatter  : null)
                 },
                 title: Ext.apply(config.yAxis.title, { style: { color: '#333333', fontWeight: 'normal' } })
             }),
             tooltip: {
                 enabled: false,
                 formatter: function() {
                           return ''+
                       (new Date(this.x)).format(Veeam.Defaults.dtFormat)
                                   + '<br />Throughput: <em>'+ tooltipFormatter.call(this) + '</em>';
                 }
             },
             plotOptions: {
                 area: {
                    shadow: false,
                    enableMouseTracking: false
                 },
                 spline: {
                    lineWidth: 3,
                    shadow: false,
                    states: {
                       hover: {
                          enabled: false,
                          lineWidth: 3
                       }
                    },
                    marker: {
                       enabled: false
                    }
                 }
             },
             credits: {
                enabled: false
             },
             legend: {
                 align: 'right',
                 layout: 'vertical',
                 verticalAlign: 'top',
                 x: 0,
                 y: 50
             }
        });

        var series = [];
        for (var i = 0, len = options.series.length; i < len; i++){
            series.push( Ext.apply({}, options.series[i]));
        }
        delete options.series;
        // insert initial dummy data
        options.series = [ { data: [null, null] , showInLegend: false }];
        var inst = this;

        this.liveChart = new Highcharts.Chart(options);

        var add = function(){
            if (series && series.length){
                for (var i =0, l = series.length; i < l; i++){
                    var dataSet = series[i];
                    dataSet['color'] = App.getChartHelper().getColorForSever( dataSet.name);
                    //dataSet['data'] = inst.reducePoints( dataSet['data'] );
                    inst.liveChart.addSeries(dataSet, true);
                }
            }
            // Add backup window
            if (options.weekly == false && config.xAxis.plotBands) {
                inst.liveChart.xAxis[0].addPlotBand(
                        Ext.apply(config.xAxis.plotBands, {
                            color: '#f4f4f4'
                        }));
            }

            inst.fireEvent('resize', inst, null, null);
            inst.liveChart.hideLoading();
            inst = null;

        };

        this.liveChart.showLoading();
        setTimeout(add, 100);
    },

    resizeHandler: function(pn, adjWidth, adjHeight, width, height){

        var h = adjHeight ? adjHeight : height ? height : Ext.fly('live-chart').getHeight();
        var w = adjWidth ? adjWidth : width ? width : Ext.fly('live-chart').getWidth();

        if (this.liveChart)
            this.liveChart.setSize( w , h, false);

    },

    reducePoints: function(data){
      return data;
    }
});

Ext.reg('vm.ui.chartandgridpanel', Veeam.ChartAndGridPanel );






