#!/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 pcr, data_ip.timestamp as timestamp from data_ts,data_ip where pcr!=0 and data_ts.run_id=$run_id and data_ts.ip=$ip and data_ts.ip_id = data_ip.id AND data_ip.id > ((SELECT MAX(id) from data_ip) - 3000)");
$sth->execute();

@array_times = ();
@array_pcr_arrive = ();

my $prev_ts = 0;
my $first_ts = 0;
$rows_count = 0;

while (my $ref = $sth->fetchrow_hashref()) {
    $rows_count++;
    my $ts = $ref->{'timestamp'};
    my $pcr = $ref->{'pcr'};

    if($prev_ts == 0){
        $prev_ts = $ts;
    };
    if($first_ts == 0){
        $first_ts = $ts;
    };

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

    push(@array_times, $time);
    push(@array_pcr_arrive, $delta_ts );
    $prev_ts = $ts;
}

$dbh->disconnect();

push(@gdata, [ @array_times ]);
push(@gdata, [ @array_pcr_arrive ]);

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     => 'Timeline (sec)',
    y_label     => 'msec',
    title       => 'PCR Arrival Interval',
    # 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	=> 500,
    x_labels_vertical	=> 0,
    # Set colors for datasets
    dclrs       => ['blue'],
) or warn $mygraph->error;

$mygraph->set_legend_font(GD::gdMediumBoldFont);
$mygraph->set_legend('PCR arrival interval');
my $myimage = $mygraph->plot(\@gdata) or die $mygraph->error;

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