#!/usr/bin/perl
# IP id <49769> time <1215331823116174606> len <1344>
#

use POSIX qw(ceil floor);
use CGI ':standard';
use GD::Graph::lines;
use DBI;
use CGI;

$query = new CGI;

$run_id = $query->param('run_id');
$ip = $query->param('ip');

$host = "localhost";
$database = "iptvprobe";
$user = "root";
$pw = "";
$connectionInfo="dbi:mysql:$database;$host";

$dbh = DBI->connect($connectionInfo,$user,$pw);
$sth = $dbh->prepare("SELECT from_unixtime(create_date) as create_date_s, run_id, timestamp, ip_pkts_count, bytes_count, lost_ip_pkts from stat_bandwidth WHERE run_id=$run_id and ip=$ip and id > ((SELECT MAX(id) from stat_bandwidth) - 300)");
$sth->execute();

@array_times = ();
@array_pkts = ();
@array_bytes = ();
@array_lost = ();

my $first_ts = 0;
my $first_create_date = 0;
$rows_count = 0;

while (my $ref = $sth->fetchrow_hashref()) {
    $rows_count++;
    my $ts = $ref->{'timestamp'};
    my $ip_pkts_count = $ref->{'ip_pkts_count'};
    my $bytes_count = $ref->{'bytes_count'}/1024;
    my $lost_ip_pkts = $ref->{'lost_ip_pkts'};

#my $create_date = $ref->{'create_date'};
#my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime( $create_date);

    if($first_ts == 0){
        $first_ts = $ts;
        $first_create_date = $ref->{'create_date_s'};
    };

    my $time = ($ts - $first_ts)/1000000000;

    push(@array_times, $time);
    push(@array_pkts, $ip_pkts_count );
    push(@array_bytes, $bytes_count );
    push(@array_lost, $lost_ip_pkts * 40);
}

$dbh->disconnect();

push(@gdata, [ @array_times ]);
push(@gdata, [ @array_pkts ]);
push(@gdata, [ @array_bytes ]);
push(@gdata, [ @array_lost ]);

if($rows_count == 0){
	print "Content-type: text/html\n\n";
	print("No data available ... \n");
};

$hsz = 1400;

my $mygraph = GD::Graph::lines->new($hsz, 400);
$mygraph->set(
    x_label     => 'Time (first is '.$first_create_date." )",
    y_label     => 'Pkts/KBytes/Lost',
    title       => 'UDP stream timeline',
    # Draw datasets in 'solid', 'dashed' and 'dotted-dashed' lines
    line_types  => [1, 2, 4],
    long_ticks  => 1,
    x_ticks	=> 1,
    # Set the thickness of line
    line_width  => 2,
    x_label_skip	=> 10,
    x_labels_vertical	=> 0,
    # Set colors for datasets
    dclrs       => ['blue', 'green', "red"],
) or warn $mygraph->error;

$mygraph->set_legend_font(GD::gdMediumBoldFont);
$mygraph->set_legend('Pkts',"Bytes", "Lost pkts");
my $myimage = $mygraph->plot(\@gdata) or die $mygraph->error;

print "Content-type: image/png\n\n";
print $myimage->png;
