#!/usr/bin/perl -w

use strict;
use CGI qw(:standard);
use Time::ParseDate;

use vars qw( $start_time $time_start );
use vars qw( $current_time $time_start_gmt );
use vars qw( %global_info @link_cc_max $e2e_cc_max );
use vars qw( $time_from $time_to );
use vars qw( $data_dir );
use vars qw( $show_ci );

require "Common.pl";

$show_ci = param( 'show_ci' );

GetDataDir();
GetStartTime() or DieEarly( "Error: GetStartTime()" );
$time_start_gmt = parsedate( $start_time, ZONE => "UTC" );
GetCurrentTime() or DieEarly( "Error: GetCurrentTime()" );
ReadGlobalInfo() or DieEarly( "Error: ReadGlobalInfo()" );
GetLinkCCmax() or DieEarly( "Error: GetLinkCCmax()" );
GetE2eCCmax() or DieEarly( "Error: GetE2eCCmax()" );

print "Content-type: text/html\n\n";
print <<EOM;
<HTML>
<HEAD>
EOM
my $link_selected = 0;
if ( ! param( 'no_refresh' ) )
{
    print "<META HTTP-EQUIV=\"REFRESH\" CONTENT=\"30; URL=ShowLinkCC.pl?";
    if ( param( 'data_id' ) )
    {
        print "data_id=".param( 'data_id' )."&";
    }
    for ( my $i = 0; $i <= $global_info{"hop_num"}; $i ++ )
    {
        if ( param( "link_$i" ) )
        {
            print "link_$i=on&";
        }
    }
    if ( param( 'from' ) )
    {
        print "from=".param( 'from' )."&";
    }
    if ( param( 'to' ) )
    {
        print "to=".param( 'to' )."&";
    }
    if ( param( 'show_ci' ) )
    {
        print "show_ci=".param( 'show_ci' )."&";
    }
    print "\">\n";
}
for ( my $i = 0; $i <= $global_info{"hop_num"}; $i ++ )
{
    if ( param( "link_$i" ) )
    {
        $link_selected = 1;
    }
}
print <<EOM;
<style type="text/css">
<!--
.style1 {
	font-size: 16px;
	font-family: "Times New Roman", Times, serif;
	background: "#DDDDDD";
}
.style2 {
	font-size: 16px;
	font-family: "Times New Roman", Times, serif;
}
.style3 {
	font-size: 32px;
	font-family: "Times New Roman", Times, serif;
	font-weight: bold;
}
-->
</style>
</HEAD>
<BODY>
EOM

GetTimePeriod();

print start_form, hidden( -name => 'data_id', -default => '' );
print <<EOM;
<TABLE WIDTH=1200 BORDER=3 CELLPADDING="0" STYLE="BORDER-COLLAPSE: COLLAPSE" ALIGN="center">
<TR ALIGN="center" BGCOLOR=#FFFF00>
<TD WIDTH=800 CLASS="style3" COLSPAN=2>Congestion Statistics of Links
EOM
print "&nbsp;&nbsp;&nbsp;&nbsp;<FONT size=3>( <A HREF=\"ShowMT.pl?data_id=".param( 'data_id' )."\" TARGET=\"_blank\"><I>MT</I></A>\n";
print "&nbsp;&nbsp;<A HREF=\"ShowMTD.pl?data_id=".param( 'data_id' )."\" TARGET=\"_blank\"><I>MTD</I></A>\n";
print "&nbsp;&nbsp;<A HREF=\"ShowQoM.pl?data_id=".param( 'data_id' )."\" TARGET=\"_blank\"><I>QoM</I></A> )</FONT>\n";
print <<EOM;
</TD>
<TD WIDTH=400 CLASS="style2">Start time: 
EOM
print "$start_time<BR>\n";
my $time_elapsed = sprintf( "%2d:%02d:%02d", $current_time / 3600, $current_time % 3600 / 60, $current_time % 60 );
print "Time elapsed: $time_elapsed";
print <<EOM;
</TD></TR>
<TR ALIGN="center"><TD CLASS="style2" BGCOLOR=#FFFF00 COLSPAN=2>
EOM
for ( my $i = 0; $i <= $global_info{"hop_num"}; $i ++ )
{
    my $checked = ( param( "link_$i" ) ? 'checked' : '' );
    print "$i".checkbox( -name => "link_$i", -label => '', -checked => $checked )."\n";
}
print $global_info{"hop_num"} + 1,
      "&nbsp;&nbsp;&nbsp;&nbsp;",
      submit( -value => "Update" ),
      "</TD>\n";
print "<TD CLASS=\"style2\" BGCOLOR=#FFFF00>",
      checkbox( -name => 'show_ci', -label => 'Congestion intensity', -onClick => 'submit()' ), "&nbsp;&nbsp;",
      checkbox( -name => 'no_refresh', -label => 'No automatic refresh', -onClick => 'submit()' ), "<BR>",
      "From: ", textfield( -name => 'from', -size => 10, -maxlength => 40, -default => $start_time ),
       " to: ", textfield( -name => 'to', -size => 10, -maxlength => 40, -default=> 'now' ),
      "</TD></TR>\n";
print "<TR>\n";
my $random_number = int( rand() * 10000000 );
my $no_refresh = ( param( 'no_refresh' ) ? "&no_refresh=on" : "" );
my $ck_show_ci = ( param( 'show_ci' ) ? "&show_ci=on" : "" );
my $count = 0;
for ( my $i = 0; $i <= $global_info{"hop_num"}; $i ++ )
{
    if ( ! $link_selected || param( "link_$i" ) )
    {
        $count ++;
        if ( PlotLinkCC( $i ) )
        {
            print "<TD WIDTH=400><TABLE ALIGN=\"center\">\n";
            print "<TR><TD ALIGN=\"center\" CLASS=\"style1\">Hop: $i-".( $i + 1 )."</TD></TR>\n";
            print "<TR><TD><A HREF=\"LinkCC_Detail.pl?data_id=".param( 'data_id' )."&link_no=$i&from=".param( 'from' )."&to=".param( 'to' )."$no_refresh$ck_show_ci\" TARGET=\"_blank\"><IMG SRC=\"images/link_$i.png?$random_number\"></A></TD></TR>\n";
            print "</TABLE></TD>\n";
        }
        if ( $count % 3 == 0 && $i != $global_info{"hop_num"} )
        {
            print "</TR><TR>\n";
        }
    }
}
if ( $count % 3 == 0 )
{
    print "</TR><TR>\n";
}
if ( PlotE2eCC() )
{
    print "<TD WIDTH=400><TABLE ALIGN=\"center\">\n";
    print "<TR><TD ALIGN=\"center\" CLASS=\"style1\">End-to-end congestion intensity</TD></TR>\n";
    print "<TR><TD><A HREF=\"LinkCC_Detail.pl?data_id=".param( 'data_id' )."&link_no=-1&from=".param( 'from' )."&to=".param( 'to' )."$no_refresh\" TARGET=\"_blank\"><IMG SRC=\"images/e2e.png?$random_number\"></A></TD></TR>\n";
    print "</TABLE></TD>\n";
}
print "</TR><TR>\n";
if ( PlotErrorMetric( 2 ) )
{
    print "<TD WIDTH=400><TABLE ALIGN=\"center\">\n";
    print "<TR><TD ALIGN=\"center\" CLASS=\"style1\">Clock skew extent</TD></TR>\n";
    print "<TR><TD><IMG SRC=\"images/error2.png?$random_number\"></A></TD></TR>\n";
    print "</TABLE></TD>\n";
}
if ( PlotErrorMetric( 3 ) )
{
    print "<TD WIDTH=400><TABLE ALIGN=\"center\">\n";
    print "<TR><TD ALIGN=\"center\" CLASS=\"style1\">Altered hop count</TD></TR>\n";
    print "<TR><TD><IMG SRC=\"images/error3.png?$random_number\"></A></TD></TR>\n";
    print "</TABLE></TD>\n";
}
if ( PlotErrorMetric( 4 ) )
{
    print "<TD WIDTH=400><TABLE ALIGN=\"center\">\n";
    print "<TR><TD ALIGN=\"center\" CLASS=\"style1\">Route alteration count</TD></TR>\n";
    print "<TR><TD><IMG SRC=\"images/error4.png?$random_number\"></A></TD></TR>\n";
    print "</TABLE></TD>\n";
}
print "</TR>\n";
print "</TABLE>\n";
print end_form;
print <<EOM;
</BODY>
</HTML>
EOM


#
# result = PlotLinkCC( $link_no )
#

sub PlotLinkCC
{
    my ( $link_no ) = @_;
    if ( open( PLOT, ">", "images/link_cc.gp" ) )
    {
        my $max_y = $link_cc_max[$link_no];
        #if ( $show_ci ) { $max_y *= 100; }
        my $min_x = $time_start + $time_from;
        my $max_x = $time_start + $time_to;
        my $center_y = $max_y / 2;
        if ( $min_x == $max_x ) { $max_x += 600; }
        print PLOT "set x2range [$min_x:$max_x]\n";
        my $increment = int( ( $max_x - $min_x ) / 1200 + 0.5 ) * 300;
        print PLOT "set x2tics mirror $increment\n";
        my $yrange = $max_y * 1.1;
        if ( $yrange == 0 ) { $yrange = 0.1 };
        print PLOT "set yrange [0:$yrange]\n";
        print PLOT "set arrow from $min_x,$center_y to $max_x,$center_y nohead lt 2\n";
        print PLOT "set ytics ( $center_y, $max_y )\n";
        print PLOT "set output \"images/link_$link_no.png\"\n";
        my $label = ( $show_ci ? "\"Cong. intensity\" at graph -0.17,-0.13 rotate" : "\"Congestion count\" at graph -0.17,-0.17 rotate" );
        print PLOT "set label $label\n";
        #my $format_y = ( $show_ci ? "%5.0f%%" : "%6.1f" );
        my $format_y = ( $show_ci ? "%6.2f" : "%6.1f" );
        print PLOT "set format y \"$format_y\"\n";
        print PLOT <<EOM;
set xlabel "Time"
set x2data time
set timefmt "%s"
set tmargin 3
unset xtics
unset ylabel
#set format x2 "%H:%M"
set ticscale 0.5
set size 0.6, 0.25
set term png
EOM
        my $data_file = ( $show_ci ? "link_ci" : "link_cc" );
        my $line_type = ( $show_ci ? "4" : "1" );
        #my $data_y = ( $show_ci ? "(\$".( $link_no + 2 )."*100)" : ( $link_no + 2 ) );
        my $data_y = $link_no + 2;
        print PLOT "plot \"$data_dir/$data_file\" using (\$1*60+$time_start):$data_y notitle w l lw 0.5 lt $line_type axis x2y1\n";
        close PLOT;
        system( "gnuplot", "images/link_cc.gp" );
        return 1;
    }
    return 0;
}


#
# result = PlotE2eCC()
#

sub PlotE2eCC
{
    if ( open( PLOT, ">", "images/link_cc.gp" ) )
    {
        my $max_y = $e2e_cc_max;
        my $min_x = $time_start + $time_from;
        my $max_x = $time_start + $time_to;
        my $center_y = $max_y / 2;
        if ( $min_x == $max_x ) { $max_x += 600; }
        print PLOT "set x2range [$min_x:$max_x]\n";
        my $increment = int( ( $max_x - $min_x ) / 1200 + 0.5 ) * 300;
        print PLOT "set x2tics mirror $increment\n";
        my $yrange = $max_y * 1.1;
        if ( $yrange == 0 ) { $yrange = 0.1 };
        print PLOT "set yrange [0:$yrange]\n";
        print PLOT "set arrow from $min_x,$center_y to $max_x,$center_y nohead lt 2\n";
        print PLOT "set ytics ( $center_y, $max_y )\n";
        print PLOT "set output \"images/e2e.png\"\n";
        print PLOT <<EOM;
set format y "%6.2f"
set xlabel "Time"
set x2data time
set timefmt "%s"
set tmargin 3
set label "Cong. intensity" at graph -0.17,-0.13 rotate
unset xtics
unset ylabel
set ticscale 0.5
set size 0.6, 0.25
set term png
EOM
        print PLOT "plot \"$data_dir/link_cc\" using (\$1*60+$time_start):". ( $global_info{"hop_num"} + 3 ) ." notitle w l lw 0.5 lt 3 axis x2y1\n";
        close PLOT;
        system( "gnuplot", "images/link_cc.gp" );
        return 1;
    }
    return 0;
}


#
# result = PlotErrorMetric( $column_no )
#

sub PlotErrorMetric
{
    my ( $column_no ) = @_;
    system( "./GetMax.sh $data_dir/error_metrics $column_no images/max_value" );
    if ( ! open( FILE, "<", "images/max_value" ) )
    {
        return 0;
    }
    my $line = <FILE>;
    close FILE;
    chomp( $line );
    my $max_y = $line;
    if ( open( PLOT, ">", "images/error_metrics.gp" ) )
    {
        my $min_x = $time_start + $time_from;
        my $max_x = $time_start + $time_to;
        my $center_y = $max_y / 2;
        if ( $min_x == $max_x ) { $max_x += 600; }
        print PLOT "set x2range [$min_x:$max_x]\n";
        my $increment = int( ( $max_x - $min_x ) / 1200 + 0.5 ) * 300;
        print PLOT "set x2tics mirror $increment\n";
        my $yrange = $max_y * 1.1;
        if ( $yrange == 0 ) { $yrange = 0.1 };
        print PLOT "set yrange [0:$yrange]\n";
        print PLOT "set arrow from $min_x,$center_y to $max_x,$center_y nohead lt 2\n";
        print PLOT "set ytics ( $center_y, $max_y )\n";
        print PLOT "set output \"images/error$column_no.png\"\n";
        print PLOT <<EOM;
set format y "%4.1f"
set xlabel "Time"
set x2data time
set timefmt "%s"
set tmargin 3
unset xtics
unset ylabel
set ticscale 0.5
set size 0.6, 0.25
set term png
EOM
        print PLOT "plot \"$data_dir/error_metrics\" using (\$1*60+$time_start):$column_no notitle w l lw 0.5 lt 8 axis x2y1\n";
        close PLOT;
        system( "gnuplot", "images/error_metrics.gp" );
        return 1;
    }
    return 0;
}

1;