<?php

require_once(dirname(__FILE__) . '/../dashlet-helper.inc.php');

dashlets_data_check();
nna_bandwidth_graph_dashlet();

function nna_bandwidth_graph_dashlet() {

	get_dashlet_dependent_request_vars($server, $host, $service);
    $source_name = grab_request_var('source', null);
    $time_period = grab_request_var('timeperiod', 24);
    $scale = grab_request_var('scale', 'linear');
    $source_id;
    $source_graph_id = null;
    $source_graph_id = gen_rand_id();
    
    global $page;
    $page = 0;
    if (isset($_REQUEST['page']))
        $page = $_REQUEST['page'];
    
    $bandwidth_data = get_server_polled_key($server, 'nna_sources_bandwidth', $limit = 1, $user_id = 0);
    $bandwidth = unpack_array($bandwidth_data[0]['nna_sources_bandwidth']);
    $sources_data = get_server_polled_key($server, 'nna_sources', $limit = 1, $user_id = 0);
    $sources = unpack_array($sources_data[0]['nna_sources']);
    
    foreach ($sources as $src) {
        if ($src['name'] == $source_name) {
            $source_id = $src['id'];
        }
    }
    $source_id = isset($source_id) ? $source_id : 0;
?>

<script>
    $(document).ready(function() {
        var current_width;
        const dashlet = $('#<?php echo $source_graph_id;?>').parent().parent().parent();
        
        // First check if any eventListe
        $(dashlet.data('events')['mousedown']).each(function(index, element){
            if(element.namespace == 'bw_graph_resize'){
                dashlet.off('mousedown.bw_graph_resize')
            }
        });
        $(dashlet.data('events')['mouseup']).each(function(index, element){
            if(element.namespace == 'bw_graph_resize_down'){
                dashlet.off('mouseup.bw_graph_resize')
            }
        });
        
        dashlet.on('mousedown.bw_graph_resize', function(){
            current_width = $(this).width();
        });
        
        dashlet.on('mouseup.bw_graph_resize', function(){
            if ($(this).width() != current_width) {
                refresh_graph('<?php echo $source_graph_id;?>')
            }
        });
        
        refresh_graph('<?php echo $source_graph_id;?>')
    });
    
    function refresh_graph(sg_id) {
        $.ajax({
            type: "GET",
            async: false,
            url: ajax_helper_url,
            data: { cmd: "get_source_bw_data", server_id: "<?php echo $server; ?>" },
            success: async function(data) {
                var bw_data = JSON.parse(data)
                
                if (bw_data != null) {
                    if ($('#' + sg_id + ' .nna_bandwidth_no_data').length){
                        $('#' + sg_id + ' .nna_bandwidth_no_data').remove();
                    }
                    load_graph(sg_id, bw_data);
                } else {
                    $('#' + sg_id).append('<p class="nna_bandwidth_no_data">' + '<?php echo _("No Data Available") ?>' + '</p>')
                    $('#' + sg_id).append('<p class="nna_bandwidth_no_data">' + '<?php echo _("Please make sure your Network Analyzer instance is running and version 2024R1+") ?>' + '</p>')
                }
            }
        })
    }

    
    // Generate a graph based on selected data and dispaly
    function load_graph(sg_id, bw_data)
    {   
        Highcharts.setOptions({ global: { useUTC: false }});
        
        var source_id = <?php echo $source_id?>;
        var selected_timeperiod = <?php echo $time_period?>;
        var scale = '<?php echo $scale?>';
        
        var selected_pointInterval = 30000;
        var selected_pointStart;
        var selected_bw_datapoints;
        
        var bw_data_len = 24/selected_timeperiod
        var bw_data_size = 288/bw_data_len

        // calculate the time difference (in seconds)
        var diff = 86400 - (3600 * selected_timeperiod)
        // convert the start time from milliseconds to seconds
        var start_time_to_sec = (bw_data[0]['bw_data'][0]['pointStart'] / 1000)
        // add the time difference to the original start time
        var add_time_diff = start_time_to_sec + diff
        // convert back to milliseconds from seconds
        var new_start_time = add_time_diff * 1000
        
        // data points used based on selected source
        bw_data.forEach(function(element){
            if(element['sid'] == source_id) {
                selected_bw_datapoints = element['bw_data']
                selected_pointStart = element['bw_data']['pointStart'];
                selected_pointInterval = element['bw_data']['pointInterval'];
            }
        });
        
        for( var i = 0; i < 4; i++ ){
            selected_bw_datapoints[i]['pointStart'] = new_start_time;
            
            // reverse the array to trim the older datasets and reverse it back after to put the data in the correct order
            selected_bw_datapoints[i]['data'].reverse();
            selected_bw_datapoints[i]['data'] = selected_bw_datapoints[i]['data'].slice(0, bw_data_size).reverse();

            selected_bw_datapoints_filtered = [];
            selected_bw_datapoints[i]['data'].forEach(function(data_point){
                if (data_point == 0) data_point = null;
                selected_bw_datapoints_filtered.push(data_point)
            });
            selected_bw_datapoints[i]['data'] = selected_bw_datapoints_filtered
        }

        var title = '<?php echo _("Bandwidth Graph") ?>';
        var text = '<?php echo _("Select or deselect the types of data to show on the graph using the legend") ?>';
        
        var series = [{
            name: bw_data[0]['bw_data'][0]['name'],
            pointInterval: bw_data[0]['bw_data'][0]['pointInterval'],
            pointStart: selected_bw_datapoints[0]['pointStart'], 
            data: selected_bw_datapoints[0]['data']
        },
        {
            name: bw_data[0]['bw_data'][1]['name'],
            pointInterval: bw_data[0]['bw_data'][1]['pointInterval'],
            pointStart: selected_bw_datapoints[0]['pointStart'],
            data: selected_bw_datapoints[1]['data'],
            visible: false
        },
        {
            name: bw_data[0]['bw_data'][2]['name'],
            pointInterval: bw_data[0]['bw_data'][2]['pointInterval'],
            pointStart: selected_bw_datapoints[0]['pointStart'],
            data: selected_bw_datapoints[2]['data'],
            visible: false
        },
        {
            name: bw_data[0]['bw_data'][3]['name'],
            pointInterval: bw_data[0]['bw_data'][3]['pointInterval'],
            pointStart: selected_bw_datapoints[0]['pointStart'],
            data: selected_bw_datapoints[3]['data'],
            visible: false
        }]
        
        var gb = 1073741824; // bytes
        var mb = 1048576;
        var kb = 1024;

        GRAPH = new Highcharts.Chart({
            chart: {
                type: 'area',
                renderTo: sg_id,
                zoomType: 'x',
                resetZoomButton: {
                    theme: {
                        display: 'none'
                    }
                },
                backgroundColor: $('html').css('background-color'),
            },
            credits: {
                enabled: false
            },
            colors: [
                '#2156c3',
                '#5e8ff6',
                '#2e2929',
                '#3216B0'
            ],
            exporting: {
                enabled: false
            },
            title: {
                text: title,
                style: {
                    color: $('html').css('color')
                }
            },
            subtitle: {
                text: text,
                style: {
                    color: $('html').css('color')
                }
            },
            xAxis: {
                type: 'datetime',
                title: {
                    text: 'Time',
                    style: {
                        color: $('html').css('color')
                    },
                },
                labels: {
                    style: {
                        color: $('html').css('color')
                    }
                }
            },
            yAxis: {
                title: {
                    text: ''
                },
                type: scale,
                labels: {
                    style: {
                        color: $('html').css('color')
                    },
                    formatter: function() {
                        var maxElement = this.value;
                        if (maxElement > gb) {
                            return (this.value / gb).toFixed(1) + " G";
                        } else if (maxElement > mb) {
                            return (this.value / mb).toFixed(1) + " M";
                        } else if (maxElement > kb) {
                            return (this.value / kb).toFixed(1) + " K";
                        } else {
                            return (this.value) + " ";
                        }
                    }
                }
            },
            tooltip: {
                formatter: function() {
                        var h = '<b>' + Highcharts.dateFormat('%m/%d/%Y %H:%M', this.x) + '</b>';

                        $.each(this.points, function(i, point) {
                            if (this.series.name == 'Bytes') {
                                var newvalue = ""
                                if (point.y > gb) {
                                    newvalue = (point.y / gb).toFixed(1) + " GB";
                                } else if (point.y > mb) {
                                    newvalue = (point.y / mb).toFixed(1) + " MB";
                                } else if (point.y > kb) {
                                    newvalue = (point.y / kb).toFixed(1) + " KB";
                                } else {
                                    newvalue = (point.y).toFixed(1) + " B";
                                }

                                h += '<br/>' + point.series.name + ': ' + newvalue;
                            } else {
                                h += '<br/>' + point.series.name + ': ' + (point.y).toFixed(0);
                            }
                        });

                        return h;
                    },
                shared: true
            },
            legend: {
                borderWidth: 0,
                itemStyle: {
                        color: $('html').css('color')
                },
                itemHoverStyle: {
                    color: '#b8b9ba'
                },
                itemHiddenStyle: {
                    color: 'gray'
                }
            },
            plotOptions: {
                area: {
                    lineWidth: 1,
                    marker: {
                        enabled: false
                    }
                }
            },
            series: series,
            function(chart) { // on complete

                chart.renderer.text('<?php echo _("No Data Available") ?>', 140, 120)
                    .css({
                        color: '#4572A7',
                        fontSize: '16px'
                    })
                    .add();

                }
        })
    }
</script>

<div id="<?php echo $source_graph_id;?>" style="height: 300px; padding: 10px; margin: 10px 0; text-align: center;">
    <!-- Main graph goes here -->
</div>


<?php } 

function gen_rand_id() {
    $id = "";
    $id = "source-graph-" . random_string(5);
    
    return $id;
}

?>
