#!/usr/bin/perl
#
#

use CGI;
use GD;
use DBI;
use lib '../include';
use nms;
use strict;
use warnings;

GD::Image->trueColor(1);

my $img = GD::Image->new('bg07.png');
#my $img = GD::Image->new(100,100);
my $cgi = CGI->new;

my $dbh = nms::db_connect();

my $sgetpoll = $dbh->prepare('select switch,(select temp from temppoll where switches.switch=temppoll.switch AND temp != 0 order by id desc limit 1) AS temp,placement from switches natural join placements');

my $black = $img->colorAllocate(0,0,0);
my $white = $img->colorAllocate(255,255,255);
my $green = $img->colorAllocate(0,255,0);
my $blue = $img->colorAllocate(0,0,255);

my $avrgtemp = 54.5;
my $mintemp = 30.0;
my $maxtemp = 55.0;
my $steps = 100;

my $color = &getcolor($avrgtemp);

open (OUT, "> /tmp/outtemps");
for (my $i = 0; $i < $steps; $i++) {
	my $diff = $maxtemp - $mintemp;
	my $temp = $mintemp + ($maxtemp - $mintemp) * ((($diff / $steps) * $i)/$diff);
	$img->line(5, $i, 45, $i, &getcolor2($temp));
}
close(OUT);

$img->string(gdMediumBoldFont, 50, 0, "Freezing!", $black);
$img->string(gdMediumBoldFont, 50, $steps - 11, "Too hot!", $black);
$img->string(gdMediumBoldFont, 50, 12, "$mintemp C", $black);
$img->string(gdMediumBoldFont, 50, $steps - 22, "$maxtemp C", $black);

#$img->string(gdMediumBoldFont, 600, 200, "Freezing!$mintemp", $black);
#$img->string(gdMediumBoldFont, 600, 210, "$mintemp C", $black);
#$img->string(gdMediumBoldFont, 600, 220 + $maxtemp, "Too hot! $maxtemp", $black);
#$img->string(gdMediumBoldFont, 600, 210 + $maxtemp, "$maxtemp C", $black);


$sgetpoll->execute();
while (my $ref = $sgetpoll->fetchrow_hashref()) {
	next if (!defined($ref->{'temp'}));

	$ref->{'placement'} =~ /\((\d+),(\d+)\),\((\d+),(\d+)\)/;
	$avrgtemp = $ref->{'temp'};
	my $px = $3;
	my $py = $4 + 16;
	my $roundtemp = sprintf ("%.0f", $avrgtemp);
	$color = getcolor($avrgtemp);
	$img->filledRectangle($px - 0, $py - 17, $px + 12, $py + 5, $white);
	$img->stringUp(gdGiantFont,$px - 1,$py - 1,"$roundtemp",$blue);
	$img->rectangle($px, $py, $px + 10,$py + 10,$black);
	$img->filledRectangle($px + 1, $py + 1, $px + 9, $py + 9,$color);
}

print $cgi->header(-type=>'image/png');
print $img->png;

sub getcolor {
	my ($temp) = @_;

	my $t = ($temp - $mintemp) / ($maxtemp - $mintemp);
	$t = 0 if ($t < 0);
	$t = 1 if ($t > 1);

	my $colorred = 255 * $t;
	my $colorblue = 255 - $colorred;

	return $img->colorResolve($colorred, 0, $colorblue);
}

sub getcolor2 {
	my ($temp) = @_;

	my $t = ($temp - $mintemp) / ($maxtemp - $mintemp);
	$t = 0 if ($t < 0);
	$t = 1 if ($t > 1);

	my $colorred = 255 * $t;
	my $colorblue = 255 - $colorred;

	return $img->colorResolve($colorred, 0, $colorblue);
}
