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


package czartool::MetricsIndex;
our @ISA = qw(czartool::Metrics);    # inherits from Metrics class

###########################################################################
#
# Constructor (overrides superclass)
#
###########################################################################
sub new {
    my ($class) = @_;

    # Call the constructor of the parent class
    my $self = $class->SUPER::new(
            $_[1],  # config object 
            $_[2],  # verbose
            $_[3]   # save_temps
            );

    # create path, dir and html file
    $self->{path} = "$self->{baseDir}";

    if ($self->{verbose}) {print "* Creating index file for metrics\n";}

    bless $self, $class;

    return $self;
}

###########################################################################
#
# Writes HTML document
#
###########################################################################
sub writeHTML {
    my ($self) = @_;

    $self->createHtml("IPP Metrics");
    my $htmlFile = $self->{htmlFile};

    opendir(DIR, $self->{path}) or die $!;

    # read metrics base dir and store contents in array
    my @days;
    my @lunations;
    while (my $dir = readdir(DIR)) {

        next if ($dir =~ m/^\./);
        next if (-f "$self->{path}/$dir");

        if ($dir =~ m/[0-9]{4}-[0-9]{2}-[0-9]{2}_.*/) {push(@lunations, $dir);}
        else { push(@days, $dir);}

    }
    closedir(DIR);

    # sort array then write to HTML
    print $htmlFile "<h2>Lunations</h2>\n";
    @lunations = sort{$b cmp $a}(@lunations);
    foreach my $lunation (@lunations) {

        print "$lunation\n";
        print $htmlFile "<a href=\"$lunation/index.html\">$lunation</a><br>\n";
    }

    # sort array then write to HTML
    my @months = qw( NA Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec );
    @days = sort{$b cmp $a}(@days);
    my $lastMonth = "NA";
    my $lastYear = "NA";
    foreach my $day (@days) {

        if ($day =~ m/^([0-9]{4})-([0-9]{2})-[0-9]{2}$/) {

            # print year, if changes
            if ($1 ne $lastYear) {
      
                print $htmlFile "<h2>$1</h2>";
                $lastYear = $1;
            }
            # print month, if changes
            if ($2 ne $lastMonth) {
      
                print $htmlFile "<h3>".$months[$2]."</h3>";
                $lastMonth = $2;
            }
            print "$day\n";
            print $htmlFile "<a href=\"$day/index.html\">$day</a><br>\n";
        }
    }

    $self->finishHtml();

    return 1;
}
1;
