#!/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 czartool::Config;
use czartool::Plotter;
use czartool::StageMetrics;

my $label = undef;
my $stage = undef;
my $save_temps = undef;
my $timeinpast = undef;
my $begin = undef;
my $end = undef;
my $day = undef;
my $path = undef;
my $verbose = undef;
my $histogram = undef;
my $timeSeries = undef;
my $rate = undef;
my $magicMask = undef;
my $rateInterval = undef;
my $deriv = undef;
my $showCleanup = undef;
my $nebulous = undef;
my $savingToFile = undef;
my $analysis = undef;
my $exposureId = undef;
my $log = undef;

GetOptions (
        "label|l=s" => \$label,
        "stage|s=s" => \$stage,
        "timeinpast|p=s" => \$timeinpast,
        "rateinterval|i=s" => \$rateInterval,
        "exposureid|x=s" => \$exposureId,
        "mask|m" => \$magicMask,
        "begin|b=s" => \$begin,
        "end|e=s" => \$end,
        "day|d=s" => \$day,
        "output|o=s" => \$path,
        "histogram|h" => \$histogram,
        "nebulous|n" => \$nebulous,
        "cleanup|c" => \$showCleanup,
        "rate|r" => \$rate,
        "deriv|f" => \$deriv,
        "analysis|a" => \$analysis,
        "timeseries|t" => \$timeSeries,
        "verbose|v" => \$verbose,
        "log|g" => \$log,
        );

print "\n*******************************************************************************\n";
print "* \n";
my $quit = 0;
if (@ARGV) {
    $quit=1;
    print "* UNKNKOWN: option                          @ARGV\n";
}
if ($analysis && !$stage) {
    $quit = 1;
    print "* REQUIRED: choose a stage for analsis      -s <chip|cam|warp|etc>      (default=none)\n";}
if (!$histogram) {
    print "* OPTIONAL: plot histogram                  -h                          (default=off)\n";}
if (!$timeSeries) {
    print "* OPTIONAL: plot timeseries                 -t                          (default=on)\n";} 
if (!$magicMask) {
    print "* OPTIONAL: plot magic mask for these times -m                          (default=off)\n";} 
if (!$exposureId) {
    print "* OPTIONAL: set exposure ID for magic mask  -x                          (default=none)\n";} 
if (!$rate) {
    print "* OPTIONAL: plot histogram of rate          -r                          (default=off)\n";} 
if (!$deriv) {
    $deriv = 0;
    print "* OPTIONAL: plot first derivative           -f                          (default=$deriv)\n";} 
if (!$analysis) {
    $analysis = 0;
    print "* OPTIONAL: include analysis                -a                          (default=$analysis)\n";} 
if (!$showCleanup) {
    $showCleanup = 0;
    print "* OPTIONAL: include cleanup in timeseries   -c                          (default=$showCleanup)\n";} 
if (!$log) {
    $log = 0;
    print "* OPTIONAL: use log plots                   -g                          (default=$log)\n";}
if (!$nebulous) {
    print "* OPTIONAL: plot nebulous disk space        -n                          (default=off)\n";} 
if (!$label) {
    $label = "all_stdscience_labels";
    print "* OPTIONAL: choose a label                  -l <labellName>             (default=$label)\n";}
if (!$stage) {
    print "* OPTIONAL: choose a stage                  -s <chip|cam|warp|etc>      (default=none)\n";}
if (!$timeinpast) {
    print "* OPTIONAL: choose time interval in past    -p <'1 hour'|'1 day'|etc>   (default=none\n";} 
if (!$rateInterval) {
    print "* OPTIONAL: time interval for rate plot     -i <'1 hour'|'1 day'|etc>   (default=depends on time frame)\n";} 
if (!$begin) {
    print "* OPTIONAL: choose a begin time             -b <datetime>               (default=6:35am this morning)\n";} 
if (!$end) {
    print "* OPTIONAL: choose an end time              -e <datetime>               (default=now)\n";} 
if (!$day) {
    print "* OPTIONAL: choose a single day to plot     -d <date>                   (default=today)\n";} 
if (!$path) {
    print "* OPTIONAL: choose an output location       -o <path>                   (default=none)\n";
} 
print "*\n*******************************************************************************\n";

if ($quit) { exit; }

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

# default values
if (!$rate && !$magicMask && !$nebulous && !$histogram && !$analysis && !$timeSeries) {$timeSeries = 1;}
if (!$verbose) {$verbose = 0;}
if (!$save_temps) {$save_temps = 0;}
if (!$path) {$savingToFile = 0; $path = ".";}
else {$savingToFile = 1;}

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

my $newDayTime =  $config->getMetricsStartTime();

my $plotter = undef; 
if ($savingToFile) {

    $plotter = czartool::Plotter->new_file($config, $path, $save_temps);
}
else {

    $plotter = czartool::Plotter->new_display($config, $save_temps);
}

# if a single day has been chosen 
if($day) {

    if ($magicMask) {

        $begin = $day;
        $end = $day;
    }
    else {

        # plots should span 24 housr from previous day
        my $dayBefore = $czarDb->subtractInterval($day, "1 DAY");
                
        $begin = "$dayBefore $newDayTime";
        $end = "$day $newDayTime";
    }
}
else {

    if (!$end) {$end = $czarDb->getNowTimestamp();}
    if (!$begin) {

        my $today = strftime('%Y-%m-%d', localtime);
        my $yesterday = $czarDb->subtractInterval($today, "1 DAY");

        
        if ($timeinpast) {$begin = $czarDb->subtractInterval($end, $timeinpast);}
        elsif ($czarDb->isBefore($end, "$today $newDayTime")) {$begin = "$yesterday $newDayTime";}
        else {$begin = "$today $newDayTime";}
    }
}

if ($rate) {

    $plotter->createRateTimeSeries($label, $stage, $begin, $end, $rateInterval);
    exit;
}
if (!$nebulous && $timeSeries) {$plotter->createTimeSeries($label, $stage, $begin, $end, $log, $showCleanup, $deriv);}
if ($histogram) {$plotter->createHistogram($label, $begin, $end);}
if ($nebulous && $timeSeries) {$plotter->plotStorageTimeSeries($begin, $end);}
elsif ($nebulous) {$plotter->plotDiskUsageHistogram();}
if ($magicMask) {

    if ($exposureId) {$plotter->plotMagicMaskFractionForThisExposure($exposureId);}
    else {$plotter->plotMagicMaskFraction($begin, $end);}

}

if($analysis) {

    my $stageMetrics = new czartool::StageMetrics($stage, $label, $begin, $end);
    if ($czarDb->runAnalysis($stageMetrics)) {$stageMetrics->printMe();}
}
