#!/usr/bin/perl -w

use warnings;
use strict;

use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );
use POSIX qw/strftime/;
use CGI::Pretty qw[:standard];

use czartool::Config;
use czartool::DayMetrics;
use czartool::MultiDayMetrics;
use czartool::MetricsIndex;

my $czarDbName = "czardb";
my $day = undef;
my $begin = undef;
my $end = undef;
my $cumulative = undef;
my $index = undef;
my $verbose = undef;
my $save_temps = undef;

GetOptions (
        "dbname=s" => \$czarDbName,
        "begin|b=s" => \$begin,
        "end|e=s" => \$end,
        "day|d=s" => \$day,
        "index|i" => \$index,
        "cumulative|c" => \$cumulative,
        "verbose|v" => \$verbose,
        );

print "\n*******************************************************************************\n";
print "* \n";
my $quit = 0;
if (@ARGV) {
    $quit=1;
    print "* UNKNKOWN: option                          @ARGV\n";
}
if (!$day) {
    print "* OPTIONAL: choose a single day                -d <date>               (default=today)\n";
}
if (!$begin) { 
    print "* OPTIONAL: choose a begin date                -b <date>               (default=today)\n";
}
if (!$end) {
    print "* OPTIONAL: choose an end date                 -e <date>               (default=today)\n";
}
if (!$cumulative) {
    print "* OPTIONAL: cumulative metrics for date range  -c                      (default=off)\n";
}
if (!$index) {
    print "* OPTIONAL: create index file for all metrics  -i                      (default=off)\n";
}

print "*\n*******************************************************************************\n";

if ($quit) {exit;}

my $config = new czartool::Config();

if ($index) {

    my $metricsIndex = new czartool::MetricsIndex($config, 1, 0);
    $metricsIndex->writeHTML();
    exit;
}

if (!$day && !$begin && !$end) {
    
    $day = strftime('%Y-%m-%d', localtime);
}
if ($day) {$begin = $end = $day;}


my $thisDay = $begin;

if ($cumulative) {

        my $multiDayMetrics = new czartool::MultiDayMetrics($config, 1, 0, $begin, $end);
        $multiDayMetrics->writeHTML();
}
else {

    my $czarDb = $config->getCzarDbInstance();

    while (1) {

        my $dayMetrics = new czartool::DayMetrics($config, 1, 0, $thisDay);
        $dayMetrics->writeHTML();

        $thisDay = $czarDb->addInterval($thisDay, "1 DAY");
        if ($czarDb->isBefore($end, $thisDay)) {last;}
    }
}

