#!/usr/bin/perl
use Apache::Request;
use Apache::Server;

my $ALBUMURL = "http://photos.lairdweb.com/webcam";
my $IMAGEDIR = "/var/media/photos/webcam";
my $IMAGEURL = "/webcam";

my $request = Apache::Request->new(shift);
#    my $log = $request->server->log;

my $uri = $request->uri;
#    $log->info("archive.pl called");

$request->content_type('text/html');
$request->send_http_header;

OutputHeader($request);
OutputDayGrid($request);
OutputFooter($request);

return(Apache::Constants::OK); 

#exit(0);

sub OutputHeader
{
    my ($r) = @_;

    print <<EOS;
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
  <head>
    <title>Highlands Ranch Webcam -- Archive</title>
    <link href="/webcam/styles.css" rel="stylesheet" type="text/css"/>
EOS
;
# '
}

sub OutputDayGrid
{
    my ($r) = @_;
    my $curyear = `date +%Y`;
    chomp($curyear);
    my $year = $r->param('year');
    $year = $curyear
    if ($year !~ /\d+/);

    print "<div class='dialogfull'>\n";
    print "<div class='dialogheader'>\n";
    print "<table border='0' cellspacing='0' cellpadding='0' width='100%'><tr>\n";
    my $lastyear = $year - 1;
    print "<td align='left'><a class='headerlink' href='archive.pl?year=$lastyear'>&lt; $lastyear</a></td>\n";
    print "<td align='center'>Webcam Archives for $year</td>\n";
        print "<!-- year: $year, curyear: $curyear -->\n";
    if($year == $curyear)
    {
        print "<td align='right'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>\n";
    }
    else
    {
        my $nextyear = $year + 1;
        print "<td align='right'><a class='headerlink' href='archive.pl?year=$nextyear'>$nextyear &gt;</a></td>\n";
    }
    print "</tr></table>\n";
    print "</div>\n";
    print "<div class='dialogcontent'>\n";
    
    # get the list of days available
    my @days = getdays($year);

    my %events = parseevents($year);

    foreach my $day (@days)
    {
        my $datestring = getdate($year,$day);
        my $img = getnoonimg($year,$day);
        print "<div class='daygrid' id='daygrid.$day' onclick=\"self.location='$ALBUMURL/$year/$day/'\" onmouseover=\"this.style.backgroundColor='#FFFF99'\" onmouseout=\"this.style.backgroundColor='white'\">\n";
        print "<img src='$IMAGEURL/$year/$day/$img' alt='$datestring' height='240' width='320'/>\n";
        print "<br/><b>$datestring</b>\n";
        if(-e "$IMAGEDIR/$year/$day/daytime.mpg")
        {
            print "<span class='linkbutton'>&nbsp;<a href='$IMAGEURL/$year/$day/daytime.mpg'>timelapse movie</a>&nbsp;</span>\n";
        }
        if($events{$day} =~ /\w/)
        {
            print "<br/><em>$events{$day}</em>\n";
        }
        else
        {
            print "<br/>&nbsp;\n";
        }
        print "</div>\n";
    }
    print "<div class='spacer'>&nbsp;</div>";
    print "</div>\n";
    print "</div>\n";
}

sub OutputFooter
{
    my ($r) = @_;
    my $date = `date`;
    print <<EOS;
  <p>
  <a href="http://validator.w3.org/check?uri=referer"><img
        src="http://www.w3.org/Icons/valid-xhtml10"
        alt="Valid XHTML 1.0 Strict" height="31" width="88" /></a>
  </p>
<hr/>
<address><a href="http://www.peterlaird.net/contact.html">Peter T. Laird &lt;plaird@pobox.com&gt;</a></address>
<p><em>
Generated: $date
</em>
</p>
</body>
</html>
EOS
;
}

### UTIL FUNCTIONS

# Return all the days which have image directories and at least one image
sub getdays
{
    my ($year) = @_;
    
    my @dirs;
    for(my $date = 0; $date < 367; $date++)
    {
        my $day = sprintf("%03d",$date);
        if(-d "$IMAGEDIR/$year/$day")
        {
            opendir(DIR,"$IMAGEDIR/$year/$day");
            my @files = readdir(DIR);
            foreach my $file (@files)
            {
                if($file =~ /\d+\.jpg/)
                {
                    push(@dirs,$day);
                    last;
                }
            }
        }
    }
    return @dirs;
}

# Get the image closest to 1:00 PM (sort of solar noon)
sub getnoonimg
{
    my($year,$day) = @_;
    
    for(my $delta = 0; $delta < 700; $delta++)
    {
        # check for plus/minus delta
        my $plustime = $day . sprintf("%04d",1300 + $delta) . ".jpg";
        my $minustime = $day . sprintf("%04d",1300 - $delta) .".jpg";
        print("<!-- Checking plus $IMAGEDIR/$year/$day/$plustime minus $IMAGEDIR/$year/$day/$minustime -->\n");
        return $plustime
            if(-e "$IMAGEDIR/$year/$day/$plustime");
        return $minustime
            if(-e "$IMAGEDIR/$year/$day/$minustime");
    }
}

# Translate the day and year into a date string
sub getdate
{
    my($year,$doy) = @_;

    use Date::Calc;
    use DateTime;
    ($year,$month,$day) = Date::Calc::Add_Delta_Days($year,1,1, $doy - 1);
    
    $dt = DateTime->new( year   => $year,
                         month  => $month,
                         day    => $day,
                         time_zone => 'America/Denver'
                         );
    
    my $datestring = $dt->day_name . ", " 
        . $dt->month_name . " "
        . $dt->day . ", "
        . $dt->year;
    
    return $datestring;
}

sub parseevents
{
    my($year) = @_;
    
    my %events = {};
    # open the events file
    if( open(EVENTS,"$IMAGEDIR/$year/.events") )
    {
        while(<EVENTS>)
        {
            if($_ =~ /^(\d+): (.*)/ )
            {
                $events{$1} = $2;
            }
        }
    }
    return %events;
}
    
