#!/usr/bin/perl -w

my $DBHOST = "127.0.0.1";
my $DBNAME = "temperature";

our $TABLE = $ARGV[0];
our $plotdir = $ARGV[1];


use DBI;
use strict;
my $gnuplot = "/usr/bin/gnuplot";
my $debug = 0;
my $font = "font '/usr/share/fonts/dejavu/DejaVuSans.ttf' 8";


# Timezone
#
my $tz = "system";
my $time = "time";
if (exists($ARGV[3]) ) { $tz= $ARGV[3]; }

# Date
#
my $day_to_plot = "now()";
if (exists($ARGV[2]) ) {
    if ( ! ($ARGV[2] eq  "now()")) {
	# "-n" to plat today - n days
	if ($ARGV[2] =~ /^[+-]?\d+\z/) {
        $DBI::result = $db->prepare("SELECT DATE(now() + INTERVAL " . int($ARGV[2]) . " DAY)");
		$DBI::result->execute();
		my ($d) = $DBI::result->fetchrow_array;
		$day_to_plot = "'$d'";
	} else {
	    	$day_to_plot = "$ARGV[2]";
	}
    }
    $debug = 1;
}
#$day_to_plot = "'2010-12-31'";
#print "date: $day_to_plot\n";


# Unit
#
#my $fahrenheit = 0;
my $t_corr= "temp/10";
my $deg_unit = "°C";

if (exists($ARGV[4]) ) {
    if ($ARGV[4] eq "f") {
#	$fahrenheit = 1;
	$t_corr = "((temp*0.18)+32)";
	$deg_unit = "°F";
    }
}


# Wait for temp deamon
if (!$debug) {
    sleep 20;
}

our $data_day = "$plotdir/temp_day_$TABLE.dat";
our $data_week = "$plotdir/temp_week_$TABLE.dat";
our $data_month = "$plotdir/temp_month_$TABLE.dat";
our $data_year = "$plotdir/temp_year_$TABLE.dat";


my $query = "SELECT ROUND($t_corr,1) AS t, HOUR($time), MINUTE($time), SECOND($time), date_format($time,'%d'), date_format($time,'%m'), date_format($time,'%Y'), date_format($time,'%W'), date_format($time,'%M'), DAYOFWEEK($time)-1, YEARWEEK($time,3), DAYOFYEAR($time), DAYOFMONTH(LAST_DAY($time)), DAYNAME($time) FROM $TABLE ";
my ($t, $hour, $minute, $second, $day, $month, $year, $dayname, $monthname, $dow, $week, $doy, $daysinmonth, $dayname2);

# min/max query
my $range_query  = "SELECT FLOOR(MAX($t_corr/10)-MIN($t_corr/10))*10 AS range1, CEIL(MAX($t_corr/10)-MIN($t_corr/10))*10 AS range2, FLOOR(MIN($t_corr/5))*5 AS min, CEIL(MAX($t_corr/5))*5 AS max FROM $TABLE ";


my $clause_daily = "WHERE DATE($time) >= DATE($day_to_plot) AND TIMESTAMP($time) <= TIMESTAMPADD(MINUTE, 60*25, $day_to_plot) ";

my $clause_weekly = "WHERE YEARWEEK($time,3) = YEARWEEK($day_to_plot,3) ";

my $clause_monthly = "WHERE YEAR($time) = YEAR($day_to_plot) and MONTH($time) = MONTH($day_to_plot)";

my $clause_yearly = "WHERE YEAR($time) = YEAR($day_to_plot) ";

my $end_clause = " ORDER BY $time";

#print $query . "\n";
#print $query . $clause_daily . $end_clause . "\n\n";
#############################################################################

my @temp_row;
my ($time_index, $line);
my ($min, $max);

$DBI::result = $db->prepare("SET time_zone = '$tz'");
$DBI::result->execute();
$DBI::result = $db->prepare("SELECT hour(now()), minute(now()), year(now()) ");
$DBI::result->execute();
my ($hour_now, $minute_now) = $DBI::result->fetchrow_array;



### Create day plot

open (DAYPLOT, ">", $data_day) or die "Can't open $data_day";

$DBI::result = $db->prepare($query . $clause_daily . $end_clause);
#print "$query . $clause_daily . $end_clause \n";
$DBI::result->execute();
my $day_index = 0;
#my $last_index = 0;
my $last_day = 0;
while(@temp_row = $DBI::result->fetchrow_array) {
	($t, $hour, $minute, $second, $day, $month, $year, $dayname, $monthname, $dow, $week, $doy, $daysinmonth) = @temp_row;
	$time_index = $hour + $minute/60 + $second/(60*60) + 0.0000001;
	if ($last_day && ($last_day != $day)) { $day_index = 24; }
	$time_index += $day_index;
	$last_day = $day;
	$time_index = substr $time_index, 0, 8;
	$line = $time_index . " $t\n";
	print DAYPLOT $line;
}
close DAYPLOT;
if (!($year)) { exit; } # Quit if no data

# Get date info for plot, last data point is next day
$DBI::result = $db->prepare($query . $clause_daily . $end_clause);
$DBI::result->execute();
@temp_row = $DBI::result->fetchrow_array;
($t, $hour, $minute, $second, $day, $month, $year, $dayname, $monthname, $dow, $week, $doy, $daysinmonth) = @temp_row;
($min, $max) = plot_bias($range_query . $clause_daily);

# Create day.gplot
open (GPLOT, ">$plotdir/day.gplot") or die "Can't open $plotdir/day.gplot";
print GPLOT "set terminal png $font size 768, 288 \n";
print GPLOT "set xtics 0, 1, 23\n";
print GPLOT "set ytics $min, 5, $max\n";
#print GPLOT "set y2tics $min, 5, $max\n";
print GPLOT "set xrange [0:24]\n";
print GPLOT "set yrange [" , $min-5 , ":" , $max+5 , "]\n";
print GPLOT "set grid xtics ytics\n";
print GPLOT "set output \"$plotdir/temp_$year$month$day.png\"\n";
#print GPLOT "set size 1.2,0.6\n";
print GPLOT "set nokey\n";
print GPLOT "set ylabel \"Temperature in $deg_unit\" offset char 0, char 0\n";
#print GPLOT "set xlabel \"Time of day (24h)\" offset char 0, char 0.5\n";
print GPLOT "set title \"Temperature $dayname $monthname $day $year\"\n";
print GPLOT "plot \"$data_day\" with lines\n";
close (GPLOT);

`$gnuplot $plotdir/day.gplot &>/dev/null`;
# `rm -f $plotdir/day.gplot $data_day`;



# Weekly plot
#
if ( ($minute_now < 5 or $minute_now > 55) or $debug) {
	open (WEEKPLOT, ">", $data_week) or die "Can't open $data_week";
	$DBI::result = $db->prepare($query . $clause_weekly . $end_clause);
	$DBI::result->execute();
	while(@temp_row = $DBI::result->fetchrow_array) {
	    ($t, $hour, $minute, $second, $day, $month, $year, $dayname, $monthname, $dow, $week, $doy, $daysinmonth) = @temp_row;	    	
	    if ($dow == 0) {$dow = 7;}
	    $time_index = $dow + $hour/24 + $minute/(60*24) + $second/(60*60*24) + 0.0000001;
	    $time_index = substr $time_index, 0, 8;
	    $line = $time_index . " $t\n";
	    print WEEKPLOT $line;
	}
	close WEEKPLOT;
	($min, $max) = plot_bias($range_query . $clause_weekly);

	my $xlegend = "";
 	my $wk_query = "select date_format(time,'%a'), day(time), weekday(time) from nattsjo_ack1 where yearweek(time,3) = yearweek(now(),3) group by weekday(time)";
	$DBI::result = $db->prepare($wk_query);
	$DBI::result->execute();
	while(@temp_row = $DBI::result->fetchrow_array) {
		my ($dn, $d, $wd) = @temp_row;
		$wd++;
		my $wd2 = $wd + 0.5;
		$xlegend = $xlegend . "'$dn $d' $wd, '' $wd2" ;
		if ($wd < 7) { $xlegend .= ", "; }		
	}

	open (GPLOT, ">$plotdir/week.gplot") or die "Can't open $plotdir/month.gplot";
	print GPLOT "set terminal png $font size 768, 288 \n";
	print GPLOT "set xtics ('Mon' 1, '' 1.5, 'Tue' 2, '' 2.5, 'Wed' 3, '' 3.5, 'Thu' 4, '' 4.5, 'Fri' 5, '' 5.5, 'Sat' 6, '' 6.5, 'Sun' 7, '' 7.5)\n";
#	print GPLOT "set xtics ($xlegend)\n";
	print GPLOT "set ytics $min, 5, $max\n";
#	print GPLOT "set y2tics $min, 5, $max\n";
	print GPLOT "set xrange [1:7+1]\n";
	print GPLOT "set yrange [" , $min-5 , ":" , $max+5 , "]\n";
	print GPLOT "set grid xtics ytics\n";
	print GPLOT "set output \"$plotdir/temp_" . $week . "w.png\"\n";
#	print GPLOT "set size 1.2,0.6\n";
	print GPLOT "set nokey\n";
	print GPLOT "set ylabel \"Temperature in $deg_unit\" offset char 0, char 0\n";
#	print GPLOT "set xlabel \"Day of week\" offset char 0, char 0.5\n";
	print GPLOT "set title \"Temperature Week " . substr($week,0,4) . " ". substr($week,4,2) . "\"\n";
	print GPLOT "plot \"$data_week\" with lines\n";
	close (GPLOT);
	`$gnuplot $plotdir/week.gplot &>/dev/null`;
#	`rm -f $plotdir/week.gplot $data_week`;



# Monthly plot
#
	open (MONTHPLOT, ">", $data_month) or die "Can't open $data_month";
	$DBI::result = $db->prepare($query . $clause_monthly . $end_clause);
	$DBI::result->execute();
	while(@temp_row = $DBI::result->fetchrow_array) {
	    ($t, $hour, $minute, $second, $day, $month, $year, $dayname, $monthname, $dow, $week, $doy, $daysinmonth) = @temp_row;
	    $time_index = $day + $hour/24 + $minute/(60*24) + $second/(60*60*24) + 0.0000001;
	    $time_index = substr $time_index, 0, 8;
	    $line = $time_index . " $t\n";
	    print MONTHPLOT $line;
	}
	close MONTHPLOT;
	($min, $max) = plot_bias($range_query . $clause_monthly);

	open (GPLOT, ">$plotdir/month.gplot") or die "Can't open $plotdir/month.gplot";
	print GPLOT "set terminal png $font size 768, 288\n";
	print GPLOT "set xtics 0, 1, $daysinmonth\n";
	print GPLOT "set ytics $min, 5, $max\n";
#	print GPLOT "set y2tics $min, 5, $max\n";
	print GPLOT "set xrange [1:$daysinmonth+1]\n";
	print GPLOT "set yrange [" , $min-5 , ":" , $max+5 , "]\n";
	print GPLOT "set grid xtics ytics\n";
	print GPLOT "set output \"$plotdir/temp_$year$month.png\"\n";
#	print GPLOT "set size 1.2,0.6\n";
	print GPLOT "set nokey\n";
	print GPLOT "set ylabel \"Temperature in $deg_unit\" offset char 0, char 0\n";
#	print GPLOT "set xlabel \"Day of month\" offset char 0, char 0.5\n";
	print GPLOT "set title \"Temperature $monthname $year\"\n";
	print GPLOT "set pointsize 0.3\n";
	print GPLOT "plot \"$data_month\" with points\n"; 
	close (GPLOT);
	`$gnuplot $plotdir/month.gplot &>/dev/null`;
#	`rm -f $plotdir/month.gplot $data_month`;
}



# Create year plot
#
if ( ($hour_now == 00 and $minute_now < 5) or $debug) {
	open (YEARPLOT, ">", $data_year) or die "Can't open $data_year";
	$DBI::result = $db->prepare($query . $clause_yearly . $end_clause);
	$DBI::result->execute();

	while(@temp_row = $DBI::result->fetchrow_array) {
	    ($t, $hour, $minute, $second, $day, $month, $year, $dayname, $monthname, $dow, $week, $doy, $daysinmonth) = @temp_row; 
	    $time_index = $doy + $hour/24 + $minute/(60*24) + $second/(60*60*24) + 0.0000001;
	    $time_index = substr $time_index, 0, 8;
	    $line = $time_index . " $t\n";
	    print YEARPLOT $line;
	}
	close YEARPLOT;
	($min, $max) = plot_bias($range_query . $clause_yearly);

	open (GPLOT, ">$plotdir/year.gplot") or
		die "Can't open $plotdir/year.gplot";
	print GPLOT "set terminal png $font size 768, 288\n";
	print GPLOT "set xtics ('Jan' 1, 'Feb' 32, 'Mar' 60, 'Apr' 91, 'May' 121, 'Jun' 152, 'jul' 182, 'Aug' 213, 'Sep' 244, 'Okt' 274, 'Nov' 305, 'Dec' 335, '' 366)\n";
        print GPLOT "set xrange [1:365+1]\n";
	print GPLOT "set ytics $min, 5, $max\n";
#	print GPLOT "set y2tics $min, 5, $max\n";
	print GPLOT "set xrange [1:365+1]\n";
	print GPLOT "set yrange [" , $min-5 , ":" , $max+5 , "]\n";
	print GPLOT "set grid xtics ytics\n";
	print GPLOT "set output \"$plotdir/temp_$year" . ".png\"\n";
#	print GPLOT "set size 1.2,0.6\n";
	print GPLOT "set nokey\n";
	print GPLOT "set ylabel \"Temperature in $deg_unit\" offset char 0, char 0\n";
#	print GPLOT "set xlabel \"Month\" offset char 0, char 0.5\n";
	print GPLOT "set title \"Temperature $year\"\n";
	print GPLOT "set pointsize 0.3\n";
	print GPLOT "plot \"$data_year\" with points\n";
	close (GPLOT);
	`$gnuplot $plotdir/year.gplot &>/dev/null`;
#	`rm -f $plotdir/year.gplot $plotdir/temp_year.dat`;
}



sub plot_bias {
	my ($minmax_query)  = @_;
	$DBI::result = $db->prepare($minmax_query);
	$DBI::result->execute();
	my ($range, $range2, $min, $max) = $DBI::result->fetchrow_array;

	if ($max-$min > 20) {
	    $max = $max-5;
	    $min = $min+5;
	} else {
	    $max = $max+5;
	    $min = $min-5;
	}
	return ($min, $max);
}