#! /usr/bin/perl

###############################################################################
#
# License
# =======
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see
#   <http://www.gnu.org/licenses/>.
#
#   Copyright (C) 2012  Jörg Sommrey
###############################################################################

use strict;
use warnings;

use CGI;

my $q = CGI->new;

my $from = $q->param('from');
my $to = $q->param('to');
my $days = $q->param('days');
my @field = $q->param('field');
my $smooth = $q->param('smooth');
my $aggr = $q->param('aggr');
my $aggrtype = $q->param('aggrtype');

$from = undef unless $from && $from =~ m{^[-0-9 /:]+$};
$to = undef unless $to && $to =~ m{^[-0-9 /:]+$};
$days = undef unless $days && $days =~ m{^\d+$};
my @allfields = split /\s+/, qx{weatherplot -list};
#    qw{barometer dewpoint extraHumid1 extraTemp1 extraTemp2 heatindex
#        inHumidity inTemp outHumidity outTemp outTempBatteryStatus rain
#        rainBatteryStatus rainRate txBatteryStatus UV windBatteryStatus
#        windDir windGust windGustDir windSpeed windchill};

@field = grep {my $field = $_; grep /^$field$/, @allfields} @field
	if @field;
$smooth = undef unless $smooth && $smooth =~ /^(no)?smooth$/;

print $q->header(-type => 'image/png');
my $cmd = "weatherplot -Terminal 'png medium truecolor'";
$cmd .= " -from '$from'" if $from;
$cmd .= " -to '$to'" if $to;
$cmd .= " -days $days" if $days;
$cmd .= " -aggr $aggr" if $aggr;
$cmd .= " -Aggrtype $aggrtype" if $aggrtype;
$cmd .= " -Field " . join(" -Field ", @field) if @field;
$cmd .= " -$smooth" if $smooth;

my $image = qx{$cmd};

print $image;
