#!/usr/local/bin/perl -w

use CGI qw/:standard :html3/;
use Date::Calc qw(Day_of_Year check_date);
use Date::EzDate;
use HTML::Escape qw/escape_html/;

print header('text/html');

my $xlatest=param("LATEST");
if ($xlatest) {
   if (($xlatest != 1)&&($xlatest != 0)) {
      errout("Invalid LATEST input\n");
   }
}
my $xyear=param("YEAR");
if ($xyear) {
   if (length($xyear)!=4) {
      errout("Invalid YEAR input\n");
   }
}
my $xmonth=param("MONTH");
if ($xmonth) {
   if (length($xmonth) > 2) {
      errout("Invalid MONTH input\n");
   }
}
my $xday=param("DAY");
if ($xday) {
   if (length($xday) > 3) {
      errout("Invalid DAY input\n");
   }
}
my $xdoy=param("DOY");
if ($xdoy) {
   if (length($xdoy) > 3) {
      errout("Invalid DOY input\n");
   }
}

my $latest=0;

my $mydate = Date::EzDate->new();
$mydate->set_warnings(0);
my $year=$mydate->{'year'};
my $month=$mydate->{'month number base1'};
my $day=$mydate->{'day of month'};
my $doy=-1;

my $eyear=-1;
my $edoy=-1;

$latest=param("LATEST");

my $scandir="/usr/local/htdocs/ACE/ASC/DATA/level3/imap_hit/quicklook_plots";
my $scanstr="hit";

if( !-d $scandir ) {
  errout("Ln34: Not a directory: $scandir\n");
}

# Early onetime fetch of all filenames
#       in given dir & with given extension
our @allfiles=();
my $file_of_files="/usr/local/htdocs/ACE/ASC/DATA/level3/imap_hit/quicklook_plots.lst";
open LOFILES,"<$file_of_files";
if (!LOFILES) {
   errout("Cannot open $file_of_files\n\t$!\n");
}
	
@allfiles = <LOFILES>;
close LOFILES;

# errout("0 First file is $allfiles[0]\n");


if (!$latest) {
   $year=param("YEAR");
   $month=param("MONTH");
   $day=param("DAY");
   $doy=param("DOY");
   if ($doy <= 0) {
      if (!check_date($year,$month,$day)) {
         errout("Year:$year  Month:$month  Day:$day  is not a valid date\n");
      }
      $doy = Day_of_Year($year,$month,$day);
      $mydate->{'year'} = $year;
      $mydate->{'dayofyearbase1'} = $doy;
   }
   else {
      # strip any leading zeros from doy
      $doy = $doy + 0;
      # calculate month and day from year and doy
      $mydate->{'year'} = $year;
      $mydate->{'dayofyearbase1'} = $doy;
      # check that the doy requested by the user does not change the year
      if ($mydate->{'year'} != $year) {
         errout("Year:$year  DayofYear:$doy is not a valid date.\n(Well it is, sortof, but I'm not sure it's what you want...)\n");
      }
      $month=$mydate->{'month number base1'};
      $day=$mydate->{'day of month'};
   }
   my $gotit = 0;
   my $origyear = $year;
   my $origdoy = $doy;
   for ($ii=0;$ii<4;$ii++) {
      if (exists_png( $scandir, $scanstr, $year, $doy)) {
         $gotit = 1;
         last;
      }
      $mydate->{'epochday'}--;
      $year = $mydate->{'year'};
      $doy = $mydate->{'dayofyearbase1'};
      $month = $mydate->{'month number base1'};
      $day = $mydate->{'day of month'};
   }
   if (!$gotit) {
      errout("Plots containing data for Year:$origyear  DayofYear:$origdoy were not found, sorry...\n");
   }
   my $edate = $mydate->clone();
   $edate->{'epochday'} +=3;
   $eyear = $edate->{'year'};
   $edoy = $edate->{'dayofyearbase1'};
}
else {
   # show webpage with plots for latest day available
   ($year,$doy,$eyear,$edoy) = cur_yrdoy_png( $scandir, $scanstr );
   if ( $year == 0 ) {
      errout("Error scanning for latest IMAP HIT quicklook plot.\n");
   }
   # calculate month and dayofmonth from year,doy
   $mydate->{'year'} = $year;
   $mydate->{'dayofyearbase1'} = $doy;
   $month=$mydate->{'month number base1'};
   $day=$mydate->{'day of month'};
}

### adds zero's to the front of doy's that are less than 3 digits
$doy = $doy + 0;
$edoy = $edoy + 0;
$doy < 10 and $doy = "0$doy";
$doy < 100 and $doy = "0$doy";
$edoy < 10 and $edoy = "0$edoy";
$edoy < 100 and $edoy = "0$edoy";

my $prevdate = $mydate->clone();
$prevdate->{'epochday'} -=1;
my $nextdate = $mydate->clone();
$nextdate->{'epochday'} +=1;
my $prevyear = $prevdate->{'year'};
my $prevmonth = $prevdate->{'month number base 1'};
my $prevday = $prevdate->{'day of month'};
my $prevdoy = $prevdate->{'dayofyearbase1'};
my $nextyear = $nextdate->{'year'};
my $nextmonth = $nextdate->{'month number base1'};
my $nextday = $nextdate->{'day of month'};
my $nextdoy = $nextdate->{'dayofyearbase1'};

my $cmd="";
my $cmd1="sed -e 's/'YYYY'/'$year'/g' -e 's/'DDD'/'$doy'/g'";
my $cmd2="-e 's/'YYY2'/'$eyear'/g' -e 's/'DD2'/'$edoy'/g'";
my $cmd3="-e 's/'MNTH'/'$month'/g' -e 's/'MDAY'/'$day'/g'";
my $cmd4="-e 's/'PYPY'/'$prevyear'/' -e 's/'PMPM'/'$prevmonth'/' -e 's/'PDPD'/'$prevday'/'";
my $cmd5="-e 's/'NYNY'/'$nextyear'/' -e 's/'NMNM'/'$nextmonth'/' -e 's/'NDND'/'$nextday'/'";
my $cmd6="< quicklook.tmpl";
$cmd = join ' ',$cmd1,$cmd2,$cmd3,$cmd4,$cmd5,$cmd6;
my @htmldata=`$cmd`;

# Adjust the year selection menu to years available in plot directory
setYearSelectionMenu(\@htmldata);


# $prevdoy = $prevdoy + 0;
# $nextdoy = $nextdoy + 0;
# $prevdoy < 10 and $prevdoy = "0$prevdoy";
# $prevdoy < 100 and $prevdoy = "0$prevdoy";
# $nextdoy < 10 and $nextdoy = "0$nextdoy";
# $nextdoy < 100 and $nextdoy = "0$nextdoy";

my $prevok = 1;
my $nextok = 1;
if (!exists_png( $scandir, $scanstr, $prevyear, $prevdoy)) {
   $prevok = 0;
}
if (!exists_png( $scandir, $scanstr, $nextyear, $nextdoy)) {
   $nextok = 0;
}
# print "prev next: $prevok $nextok<br>";

my $idx=0;
for ($idx=0; $idx<=$#htmldata; $idx++) {
   if ($htmldata[$idx] =~ m/!YEAR/ ) {
      my ($junk1, $curryear, $junk2) = split /"/, $htmldata[$idx];
      if ($curryear == $year) {
         $htmldata[$idx] =~ s/option/option selected/;
      }
   }
   if ($htmldata[$idx] =~ m/!MONTH/ ) {
      my ($junk3, $currmonth, $junk4) = split /"/, $htmldata[$idx];
      if ($currmonth == $month) {
         $htmldata[$idx] =~ s/option/option selected/;
      }
   }
   if ($htmldata[$idx] =~ m/!DAY/ ) {
      my ($junk5, $currday, $junk6) = split /"/, $htmldata[$idx];
      if ($currday == $day) {
         $htmldata[$idx] =~ s/option/option selected/;
      }
   }
   if (($htmldata[$idx] =~ m/Next plot/ ) && ($nextok == 0)){
      $htmldata[$idx] = "<font color=\"gray\">Next plot</font>";
   }
   if (($htmldata[$idx] =~ m/Previous plot/ ) && ($prevok == 0)){
      $htmldata[$idx] = "<font color=\"gray\">Previous plot</font>";
   }
}

$scandir=$scandir . "/" . $year . "/" . $doy;
if (!exists_png( $scandir, $scanstr, $year, $doy)) {
for ($idx=0; $idx<=$#htmldata; $idx++) {
   if ($htmldata[$idx] =~ m/Plots in PDF Format/ ) {
      $htmldata[$idx] = "\n";
   }
   if ($htmldata[$idx] =~ m/For a full-size plot/ ) {
      $htmldata[$idx] = "<b>No plots found for the day requested</b>\n";
   }
}
#   errout("Error scanning for SIT $sc housekeeping plots for $year $doy.\n");
}

print @htmldata;

exit(0);


###=======   setYearSelectionMenu   ==========

sub setYearSelectionMenu {
  my ( $rhtml )= $_[0];
  our @allfiles;

  # Get years of 1st and last plots in directory
  # use names in @allfiles

  my @temp = ();
  my $ptrn = "_(\\d\\d\\d\\d)_(\\d\\d\\d)_(\\d\\d\\d\\d)_(\\d\\d\\d)";
  $allfiles[0] =~ /$ptrn/ ;
  my $firstYear = $1;
  $allfiles[$#allfiles] =~ /$ptrn/ ;
  my $lastYear = $3;

  # Append new option values in year selection menu
  my $idx = -1;
  @temp = ();   # Start with whole new @htmldata array of strings
  my $i = 0;
  while( $i <= $#$rhtml ) {
    last if( $$rhtml[$i] =~ /<!YEAR> <option VALUE/ ) ;
    push @temp, $$rhtml[$i];    # copy all up to the Selection YEAR menu
    $i++;
  }
  $idx = $i;
  # insert the new option values for sel menu (year values)
  for( my $i=$firstYear; $i<=$lastYear; $i++ ) {
    my $str = sprintf "<!YEAR> <option VALUE=\"%4d\">%4d\n", $i, $i ;
    push @temp, $str;
  }
  while( $$rhtml[$idx] =~ /option VALUE/ ) {
    $idx++;
    next;
  }
  for( my $i=$idx; $i<=$#$rhtml; $i++ ) {
    push @temp, $$rhtml[$i];    # append all remaining to the @temp
  }
  @$rhtml = ();                 # Rewrite the $htmldata array
  push @$rhtml, @temp;

  return;
}


sub errout {
        my ( $message )= @_;
        my $escaped = escape_html($message);
         print start_html('Error Message');
         print "<pre>$escaped</pre>\n";
         print end_html;
         exit(1);
}

###	$directory/$string_$Year_$DayofYear_hskp_0.jpg,
###     where $directory, $string, $year, and $dayofyear are parameters 
###	provided by the calling routine.
###     $year is a four-digit year, and $dayofyear is a three-digit DayofYear.
###     Return TRUE (Non-zero) if the pattern is matched, FALSE (0) otherwise.
###

### Initialization 
sub exists_png {
  
  # Check command line args
  return 0 if( $#_ != 3 );
  my ($dir, $strng, $year, $DOY) = @_ ;
  our @allfiles;
  
  return( 0 ) if( ! -d $dir ) ;		# is directory?
  
  # Get names of all "_hskp_0.jpg" files
#  opendir( HKDIR, $dir ) or return( 0 );
#  my @allfiles = grep { /.jpg$/ } readdir HKDIR;
#  print @allfiles;

  return( 0 ) if( $#allfiles < 0 );

  
# Look for the specific string/date match
  $DOY = $DOY + 0;
  $DOY < 10 and $DOY = "0$DOY";
  $DOY < 100 and $DOY = "0$DOY";
  
  my $i=0;
  my $ptrn = "${strng}_${year}_${DOY}_";
  while( $i <= $#allfiles ) {
    return( 1 ) if( $allfiles[$i] =~ $ptrn ) ; # Matches ??
    $i++;
  }
  
  return( 0 );		# no match
}



###     find the file with
###	the most recent year and doy, and return that year and doy 
###	to the calling routine (in some simple data structure).
###	If no files matching the pattern are found, then return 0,0.
###

### Initialization 
sub cur_yrdoy_png {
  
  # Check command line args
  return 0 if( $#_ != 1 );
  my ($dir, $strng) = @_ ;
  return( 0, 0 ) if( ! -d $dir ) ;		# is directory?
  
  # Get names of all "pdf" files
  # opendir( HKDIR, $dir ) or return( 0 );
  # my @allfiles = grep { /_hskp.pdf$/ } readdir HKDIR;
  # my @alldirs = <$dir/*>;
  # return( 0, 0 ) if( $#alldirs < 0 );
  # my @allfiles = <$dir/${strng}*.pdf>;
  # print @allfiles;
  # return( 0, 0 );
  our @allfiles;

#  errout("First file is $allfiles[0]\n");
  
  return( 0, 0 ) if( $#allfiles < 0 );

  my $val = 0;
  #latest date is the last member of the list...
  my $ptrn = "_(\\d\\d\\d\\d)_(\\d\\d\\d)_(\\d\\d\\d\\d)_(\\d\\d\\d)";

  $allfiles[$#allfiles] =~ /$ptrn/ ;	# Extract yr & DOY
  $val = ($1 * 1000) + $2 ;
  return(0,0) if( $val <= 0 );		# in case none found

  $yr1 = $1;
  $doy1= $2;
  $yr2 = $3;
  $doy2= $4;
  return( $yr1, $doy1, $yr2, $doy2 ) ; # Largest/Latest date ??
}

