#!/usr/bin/perl -w                                                             
use DBI; 

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

my $font = "font '/usr/share/fonts/dejavu/DejaVuSans.ttf' 8";

$DBI::result = $db->prepare("SELECT year(now()), date_format(now(),'%m'), date_format(now(),'%d'), date_format(now(),'%W'), date_format(now(),'%M'), week(now(),3), yearweek(now(),3), DAYOFMONTH(LAST_DAY(now()))");
$DBI::result->execute();
@temp_row = $DBI::result->fetchrow_array; 
my ($year, $month, $day, $dayname, $monthname, $week_no, $yearweek, $daysinmonth) = @temp_row;
#undef $db;

my $label1 = "Ack1";
my $label2 = "Solar_in";
my $label3 = "Solar_out";
my $label4 = "Indoor";
my $label5 = "Outdoor";

my $table1 = "nattsjo_ack1";
my $table2 = "nattsjo_solarin";
my $table3 = "nattsjo_solarout";
my $table4 = "nattsjo_indoor1";
my $table5 = "nattsjo_outdoor1";

my $plotdir = "/home/http-user/flasher-root/temp/nattsjo_control/plots";
my $datadir = "/home/http-user/flasher-root/temp";
my $file_day_suffix = "temp_day_";
my $datafile1 = "$datadir/$table1/plots/$file_day_suffix$table1.dat";
my $datafile2 = "$datadir/$table2/plots/$file_day_suffix$table2.dat";
my $datafile3 = "$datadir/$table3/plots/$file_day_suffix$table3.dat";
my $datafile4 = "$datadir/$table4/plots/$file_day_suffix$table4.dat";
my $datafile5 = "$datadir/nattsjo/plots/$file_day_suffix$table5.dat";

# Ack1
my ($min1, $max) = plot_bias("$datadir/$table1/plots/$file_day_suffix$table1.dat", "");
# Solar_in
my ($min2, $max2) = plot_bias("$datadir/$table2/plots/$file_day_suffix$table2.dat", "");
# Ack1 min > 30
if ($min1 > 30) {
    ($min1, $max) = plot_bias("$datadir/$table4/plots/$file_day_suffix$table4.dat", "");
}

# indoor > ack
my ($min4, $max4) = plot_bias("$datadir/$table4/plots/$file_day_suffix$table4.dat", "");
if ($max4 > $max) { $max = $max4; }

# Solar > ack1 or indoor
if ($max2 > $max) { $max = $max2; }

my ($min, $max1) = plot_bias("$datadir/nattsjo/plots/$file_day_suffix$table5.dat", "");

#if ($max > 25) { $max = 25; };
if ($max < 15) { $max = 15; };
if ($min <  0) { $min = 0; };
if ($min >  5) { $min = 5; };

### Create day.gplot                                                            
open (GPLOT, ">$plotdir/day.gplot") or
    die "Can't open $plotdir/day.gplot";
print GPLOT "set terminal png $font 8 size 768, 288 \n";
print GPLOT "set xtics 0, 1, 23\n";
print GPLOT "set ytics $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 key right\n";
print GPLOT "set ylabel \"Temperature in &deg;C\" 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 '$datafile1' ti '$label1' with lines, '$datafile2' ti '$label2'  with lines, '$datafile3' ti '$label3' with lines, '$datafile4' ti '$label4' with lines, '$datafile5' ti '$label5' with lines\n";
close (GPLOT);


# select max(a.temp), min(b.temp) from nattsjo_ack1 a, nattsjo_outdoor1 b where date(b.time) = date(now()) and date(a.time) = date(now()) ;


my $file_week_suffix = "temp_week_";
$datafile1 = "$datadir/$table1/plots/$file_week_suffix$table1.dat";
$datafile2 = "$datadir/$table2/plots/$file_week_suffix$table2.dat";
$datafile3 = "$datadir/$table3/plots/$file_week_suffix$table3.dat";
$datafile4 = "$datadir/$table4/plots/$file_week_suffix$table4.dat";
$datafile5 = "$datadir/nattsjo/plots/$file_week_suffix$table5.dat";

($min1, $max) = plot_bias("$datadir/$table1/plots/$file_week_suffix$table1.dat", "");
($min2, $max2) = plot_bias("$datadir/$table2/plots/$file_week_suffix$table2.dat", "");

if ($min1 > 30) {
    ($min1, $max) = plot_bias("$datadir/$table4/plots/$file_week_suffix$table4.dat", "");
}
# Solar > ack1 or indoor
if ($max2 > $max) { $max = $max2; }

($min, $max1) = plot_bias("$datadir/nattsjo/plots/$file_week_suffix$table5.dat", "");
#if ($max > 25) { $max = 25; };
if ($max < 15) { $max = 15; };
if ($min <  0) { $min = 0; };
if ($min >  5) { $min = 5; };

### Create week.gplot

	my $xlegend = "";
 	my $wk_query = "select date_format(time,'%a'), day(time), weekday(time) from nattsjo_ack1 where yearweek(time,3) = yearweek('2012-06-30',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/week.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 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_$yearweek" . "w.png'\n";
print GPLOT "set key right\n";
print GPLOT "set ylabel 'Temperature in &deg;C' 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 $year $week_no'\n";
#print GPLOT "plot '$datafile1' ti '$label1' with lines, '$datafile2' ti '$label2'  with lines, '$datafile3' ti '$label3' with lines, '$datafile4' ti '$label4' with lines, '$datafile5' ti '$label5' with lines\n";
print GPLOT "plot '$datafile1' ti '$label1' with points pointsize 0.2, '$datafile2' ti '$label2' with lines, '$datafile3' ti '$label3' with lines, '$datafile4' ti '$label4' with points pointsize 0.2, '$datafile5' ti '$label5' with points pointsize 0.15\n";

close (GPLOT);

`gnuplot  $plotdir/day.gplot $plotdir/week.gplot `;


#my $daysinmonth = 31;


my $file_month_suffix = "temp_month_";
$datafile1 = "$datadir/$table1/plots/$file_month_suffix$table1.dat";
$datafile2 = "$datadir/$table2/plots/$file_month_suffix$table2.dat";
$datafile3 = "$datadir/$table3/plots/$file_month_suffix$table3.dat";
$datafile4 = "$datadir/$table4/plots/$file_month_suffix$table4.dat";
$datafile5 = "$datadir/nattsjo/plots/$file_month_suffix$table5.dat";

($min1, $max) = plot_bias("$datadir/$table1/plots/$file_month_suffix$table1.dat", "");
($min2, $max2) = plot_bias("$datadir/$table2/plots/$file_month_suffix$table2.dat", "");
if ($min1 > 30) {
    ($min1, $max) = plot_bias("$datadir/$table4/plots/$file_month_suffix$table4.dat", "");
}
# Solar > ack1 or indoor
if ($max2 > $max) { $max = $max2; }


($min, $max1) = plot_bias("$datadir/nattsjo/plots/$file_month_suffix$table5.dat", "");
#if ($max > 25) { $max = 25; };
if ($max < 15) { $max = 15; };
if ($min <  0) { $min = 0; };
if ($min >  5) { $min = 5; };

### Create month.gplot

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 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 key right\n";
print GPLOT "set ylabel \"Temperature in &deg;C\" 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 "plot '$datafile1' ti '$label1' with lines, '$datafile2' ti '$label2'  with lines, '$datafile3' ti '$label3' with lines, '$datafile4' ti '$label4' with lines, '$datafile5' ti '$label5' with lines\n";
print GPLOT "plot '$datafile1' ti '$label1' with points pointsize 0.2, '$datafile2' ti '$label2' with lines, '$datafile3' ti '$label3' with lines, '$datafile4' ti '$label4' with points pointsize 0.2, '$datafile5' ti '$label5' with points pointsize 0.1\n";

close (GPLOT);
`gnuplot  $plotdir/month.gplot `;




sub plot_bias {
    my ($filename, $minmax_query)  = @_;
    my ($tmp, $min, $max, $line);
    my @tmp;
    $range = 10;

    open (MINMAX, "$filename") or
	    die "Can't open $filename";
    $min = 100;
    $max = -100;

    while ($line = <MINMAX>) {
	@tmp = split ' ', $line;
	chomp $tmp[1];
	if ($tmp[1] > $max) { $max = $tmp[1]; }
	if ($tmp[1] < $min) { $min = $tmp[1]; }
    }
    close MINMAX;
    $min--;
    $max++;
    
    if ($min < -$range/2) {
	$min = (abs($min / 5) % 100) * -5;
	$max = $min + $range;
    } elsif ($max > $range/2) {
	$max = (($max / 5) % 100) * 5;
	$min = $max - $range;
    } else {
	$max = $range/2;
	$min = -$range/2;
    }
    return ($min, $max);
}