#!/usr/bin/perl
#
# Export files from the rings into a format that is suitable for display
# as a static website.

use strict;
use Cwd;
use DBI;
use File::HomeDir;
use Getopt::Long;
use Pod::Usage;
use Rings::Common;

my %PROPS;
my $opt_debug;
my $opt_conf;
my $opt_example;
my $opt_help;
my $opt_manual;
my $opt_properties;

##############################################################################
# Subroutines
##############################################################################

# ------------------------------------------------
# Print an example properties file

sub display_example {

    print "# The output path\n";
    print "#\n";
    print "path = /some/output/directory\n";

    print "#\n";
    print "# MySQL WHERE clause without the WHERE using the tables \n";
    print "# picture_rings d and pictures_information p.\n";
    print "#\n";
    print "# picture_rings d\n";
    print "#  uid\n";
    print "#  pid\n";
    print "#\n";
    print "# pictures_information p\n";
    print "#  pid\n";
    print "#  source_file\n";
    print "#  key_words\n";
    print "#  file_name\n";
    print "#  date_taken\n";
    print "#  picture_date\n";
    print "#  taken_by\n";
    print "#  description\n";
    print "#  grade\n";
    print "#  public\n";
    print "#  camera\n";
    print "#  shutter_speed\n";
    print "#  fstop\n";
    print "#  date_last_maint\n";
    print "#  date_added\n";
    print "#\n";
    print "selection = uid='zid-1969-macallister-slides-1'\n";

    print "#\n";
    print "# Output HTML\n";
    print "#\n";
    print "html = 1\n";

    print "#\n";
    print "# Output raw image\n";
    print "#\n";
    print "raw = 1\n";

    print "#\n";
    print "# Output thumb image\n";
    print "#\n";
    print "thumb = 1\n";

    print "#\n";
    print "# Output large image\n";
    print "#\n";
    print "large = 1\n";

    print "#\n";
    print "# Output larger image\n";
    print "#\n";
    print "larger = 1\n";

    print "#\n";
    print "# Output largest image\n";
    print "#\n";
    print "largest = 1\n";

    return;
}

# ------------------------------------------------
# test boolean

sub test_boolean {

    my ($in) = @_;
    $in =~ s/\s+//g;
    $in =~ lc($in);

    my $result = 0;

    if ($in =~ /^(\d+)$/) {
        if ($1 != 0) {
            $result = 1;
        }
    } elsif ($in =~ /^true$/) {
        $result = 1;
    } elsif ($in =~ /^yes$/) {
        $result = 1;
    }

    return $result;

}

# ------------------------------------------------
# read the properties

sub read_properties {
    my ($pfile) = @_;
    if (!-e $pfile) {
        if ($opt_debug) {
            dbg("Properties file not found: $pfile");
        }
        return;
    }

    if ($opt_debug) {
        dbg("Reading properties file: $pfile");
    }

    open(f, '<', $pfile);
    while (<f>) {
        if (!/^\#/) {
            if (/^\s*(.*?)\=(.*)$/) {
                my $attr = $1;
                my $val  = $2;
                $attr =~ s/^\s+//;
                $attr =~ s/\s+$//;
                $val  =~ s/^\s+//;
                $val  =~ s/\s+$//;
                $PROPS{$attr} = $val;
            }
        }
    }
    close f;
    return;
}

# ------------------------------------------------
# write a file to disk

sub write_file {

    my ($f, $c) = @_;
    if ($opt_debug) {
        dbg("writing file:$f");
    }
    open(outfile, '>', $PROPS{'path'} . $f);
    print outfile $c;
    close outfile;
}

# ------------------------------------------------
# write html to display the image

sub write_html {

    my (
        $last_f, $this_f, $this_i, $next_f, $lfile, $ltitle,
        $mfile,  $mtitle, $rfile,  $rtitle, $desc,  $pid
    ) = @_;

    # -- get list of people, places
    my $sel = "SELECT ";
    $sel .= "p.display_name ";
    $sel .= "FROM picture_rings d ";
    $sel .= "JOIN people_or_places p ";
    $sel .= "ON (d.uid = p.uid) ";
    $sel .= "WHERE d.pid='$pid' ";
    $sel .= "AND p.display_name NOT LIKE 'ZID%' ";
    $sel .= "ORDER BY p.display_name ";

    if ($opt_debug) {
        dbg($sel);
    }

    my $sth = $DBH->prepare($sel);
    $sth->execute();
    if ($sth->err) {
        sql_die($sel, $sth->err, $sth->errstr);
    }
    my @names;
    my $name_cnt = 0;

    while (my $row = $sth->fetchrow_hashref) {
        push @names, $row->{display_name};
        $name_cnt++;
    }

    # -- Create HTML
    open(f, '>', $PROPS{'path'} . $this_f);
    print f "<html>\n";
    print f "<head>\n";
    print f "<title>Picture Show</title>\n";
    print f "</head>\n";
    print f "\n";
    print f "<body bgcolor=\"#000000\">\n";
    print f "\n";
    print f "<div align=\"center\">\n";
    print f "<table border=\"0\">\n";

    # -- next-previous buttons
    print f "<tr>\n";
    print f " <td>";
    if (length($last_f) == 0) {
        print f "&nbsp;";
    } else {
        print f "<a href=\"$last_f\">";
        print f "<font color=\"#ffffff\" ";
        print f "face=\"Arial, Helvetica, sans-serif\"><b>";
        print f "Previous Image";
        print f "</b></font>";
        print f "</a>";
    }
    print f " </td>\n";

    print f " <td>&nbsp;</td>\n";

    print f " <td align=\"right\">";
    if (length($next_f) == 0) {
        print f "&nbsp;";
    } else {
        print f "  <a href=\"$next_f\">";
        print f "<font color=\"#ffffff\" ";
        print f "face=\"Arial, Helvetica, sans-serif\"><b>";
        print f "Next Image";
        print f "</b></font>";
        print f "</a>";
    }
    print f " </td>\n";
    print f "</tr>\n";

    # -- the picture
    print f "<tr>\n";
    print f " <td colspan=\"3\" align=\"center\"><img src=\"$this_i\"></td>\n";
    print f "</tr>\n";

    # -- the description
    if (length($desc) > 0) {
        print f "<tr>\n";
        print f " <td colspan=\"3\" align=\"center\" width=\"600\">";
        print f "<font color=\"#ffffff\" ";
        print f "face=\"Arial, Helvetica, sans-serif\"><b>";
        print f $desc;
        print f "</b></font>";
        print f "</td>\n";
        print f "</tr>\n";
    }

    # -- the names
    if ($name_cnt > 0) {
        print f "<tr>\n";
        print f " <td colspan=\"3\" align=\"center\" width=\"600\">";
        print f "<font color=\"#ffffff\" ";
        print f "face=\"Arial, Helvetica, sans-serif\"><b>";
        foreach my $n (@names) {
            print f "$n&nbsp;&nbsp;";
        }
        print f "</b></font>";
        print f "</td>\n";
        print f "</tr>\n";
    }

    # -- image size stuff
    print f "<tr>\n";
    print f " <td align=\"left\" width=\"33%\">\n";
    print f "  <a href=\"$lfile\">";
    print f "<font color=\"#ffffff\" ";
    print f "face=\"Arial, Helvetica, sans-serif\"><b>";
    print f $ltitle;
    print f "</b></font>";
    print f "</a>\n";
    print f " </td>\n";
    print f " <td align=\"center\" width=\"33%\">\n";
    print f "  <a href=\"$mfile\">";
    print f "<font color=\"#ffffff\" ";
    print f "face=\"Arial, Helvetica, sans-serif\"><b>";
    print f $mtitle;
    print f "</b></font>";
    print f "</a>\n";
    print f " </td>\n";
    print f " <td align=\"right\" width=\"33%\">\n";
    print f "  <a href=\"$rfile\">";
    print f "<font color=\"#ffffff\" ";
    print f "face=\"Arial, Helvetica, sans-serif\"><b>";
    print f $rtitle;
    print f "</b></font>";
    print f "</a>\n";
    print f " </td>\n";
    print f "</tr>\n";

    # -- the index
    print f "<tr>\n";
    print f " <td colspan=\"3\" align=\"center\">";
    print f"<a href=\"index.html\">";
    print f "<font color=\"#ffffff\" ";
    print f "face=\"Arial, Helvetica, sans-serif\"><b>";
    print f "Index";
    print f "</b></font>";
    print f "</a>\n";
    print f " </td>\n";
    print f "</tr>\n";

    print f "\n";
    print f "</table>\n";
    print f "</div>\n";
    print f "\n";

    print f "</body>\n";
    print f "</html>\n";

    close f;

}

# ------------------------------------------------
# process the files

sub read_and_write {

    # -- get a list of picture ids

    my $sel = "CREATE TEMPORARY TABLE tmp_picture_list ";
    $sel .= "SELECT DISTINCT d.pid ";
    $sel .= "FROM picture_rings d ";
    $sel .= "JOIN pictures_information p ";
    $sel .= "ON d.pid=p.pid ";
    $sel .= "WHERE " . $PROPS{'selection'} . " ";

    if ($opt_debug) {
        dbg($sel);
    }

    my $sth = $DBH->prepare($sel);
    $sth->execute();
    if ($sth->err) {
        sql_die($sel, $sth->err, $sth->errstr);
    }
    $sth->finish();

    # -- Loop through the pictures

    my $sel = "SELECT ";
    $sel .= "pic.picture_date picture_date, ";
    $sel .= "pic.description description, ";
    $sel .= "pic.pid pid ";
    $sel .= "FROM  pictures_information pic ";
    $sel .= "JOIN tmp_picture_list tmp ";
    $sel .= "ON (tmp.pid = pic.pid) ";
    $sel .= "ORDER BY pic.picture_date ";

    if ($opt_debug) {
        dbg($sel);
    }

    my $sth = $DBH->prepare($sel);
    $sth->execute();
    if ($sth->err) {
        sql_die($sel, $sth->err, $sth->errstr);
    }

    my $hfile_index = 'index.html';
    my $index_html  = '';

    # -- create the thumbnail index
    $index_html .= "<html>\n";
    $index_html .= "<head>\n";
    $index_html .= "<title>Picture Index</title>\n";
    $index_html .= "</head>\n";
    $index_html .= "\n";
    $index_html .= "<body bgcolor=\"#000000\">\n";
    $index_html .= "\n";

    $index_html .= "<div align=\"center\">\n";
    $index_html .= "<table border=\"1\"><tr><td>\n";
    $index_html .= "\n";
    my $i_per = 6;
    my $i_cnt = 0;

    my $last_hfile         = '';
    my $last_hfile_large   = '';
    my $last_hfile_larger  = '';
    my $last_hfile_largest = '';
    my $this_hfile         = '';
    my $this_hfile_large   = '';
    my $this_hfile_larger  = '';
    my $this_hfile_largest = '';
    my $next_hfile         = '';
    my $next_hfile_large   = '';
    my $next_hfile_larger  = '';
    my $next_hfile_largest = '';

    my $pfile         = '';
    my $pfile_small   = '';
    my $pfile_large   = '';
    my $pfile_larger  = '';
    my $pfile_largest = '';

    my $this_desc = '';
    my $this_pid  = '';

    while (my $row = $sth->fetchrow_hashref) {

        dbg("Processing $row->{pid} $row->{picture_date}");

        my $img_sel = "SELECT ";
        $img_sel .= "rw.picture raw, ";
        $img_sel .= "lgst.picture lgst, ";
        $img_sel .= "lgr.picture lgr, ";
        $img_sel .= "lg.picture lg, ";
        $img_sel .= "sm.picture sm ";
        $img_sel .= "FROM pictures_raw rw ";
        $img_sel .= "JOIN pictures_1280_1024 lgst ";
        $img_sel .= "ON (lgst.pid = rw.pid) ";
        $img_sel .= "JOIN pictures_larger lgr ";
        $img_sel .= "ON (lgr.pid = rw.pid) ";
        $img_sel .= "JOIN pictures_large lg ";
        $img_sel .= "ON (lg.pid = rw.pid) ";
        $img_sel .= "JOIN pictures_small sm ";
        $img_sel .= "ON (sm.pid = rw.pid) ";
        $img_sel .= "WHERE rw.pid = '$row->{pid}' ";

        if ($opt_debug) {
            dbg($img_sel);
        }

        my $img_sth = $DBH->prepare($img_sel);
        $img_sth->execute();
        if ($img_sth->err) {
            sql_die($img_sel, $img_sth->err, $img_sth->errstr);
        }

        if (my $img_row = $img_sth->fetchrow_hashref) {

            my $pic_root = 'PIC-' . $row->{picture_date} . '-' . $row->{pid};
            $pic_root =~ s/\s+//g;
            $pic_root =~ s/://g;

            # -- html output
            if (test_boolean($PROPS{'html'})) {
                # -- html file names
                my $next_hfile         = $pic_root . '-raw.html';
                my $next_hfile_large   = $pic_root . '-large.html';
                my $next_hfile_larger  = $pic_root . '-larger.html';
                my $next_hfile_largest = $pic_root . '-largest.html';

                # -- write the previous html file
                if (length($this_hfile) > 0) {
                    write_html(
                        $last_hfile,         $this_hfile,
                        $pfile,              $next_hfile,
                        $this_hfile_large,   'Large',
                        $this_hfile_larger,  "Larger",
                        $this_hfile_largest, "Largest",
                        $this_desc,          $this_pid
                    );
                    write_html(
                        $last_hfile_large,   $this_hfile_large,
                        $pfile_large,        $next_hfile_large,
                        $this_hfile,         'Raw',
                        $this_hfile_larger,  "Larger",
                        $this_hfile_largest, "Largest",
                        $this_desc,          $this_pid
                    );
                    write_html(
                        $last_hfile_larger,  $this_hfile_larger,
                        $pfile_larger,       $next_hfile_larger,
                        $this_hfile,         'Raw',
                        $this_hfile_large,   "Large",
                        $this_hfile_largest, "Largest",
                        $this_desc,          $this_pid
                    );
                    write_html(
                        $last_hfile_largest, $this_hfile_largest,
                        $pfile_largest,      $next_hfile_largest,
                        $this_hfile,         'Raw',
                        $this_hfile_large,   "Large",
                        $this_hfile_larger,  "Larger",
                        $this_desc,          $this_pid
                    );
                }
                $last_hfile         = $this_hfile;
                $last_hfile_large   = $this_hfile_large;
                $last_hfile_larger  = $this_hfile_larger;
                $last_hfile_largest = $this_hfile_largest;
                $this_hfile         = $next_hfile;
                $this_hfile_large   = $next_hfile_large;
                $this_hfile_larger  = $next_hfile_larger;
                $this_hfile_largest = $next_hfile_largest;
                $this_desc          = $row->{description};
                $this_pid           = $row->{pid};

                # -- image file names
                $pfile         = $pic_root . '-raw.jpg';
                $pfile_small   = $pic_root . '-thumb.jpg';
                $pfile_large   = $pic_root . '-large.jpg';
                $pfile_larger  = $pic_root . '-larger.jpg';
                $pfile_largest = $pic_root . '-largest.jpg';

                # -- write the image files
                write_file($pfile,         $img_row->{raw});
                write_file($pfile_small,   $img_row->{sm});
                write_file($pfile_large,   $img_row->{lg});
                write_file($pfile_larger,  $img_row->{lgr});
                write_file($pfile_largest, $img_row->{lgst});

                # -- generate index html
                if ($i_cnt == 0) {
                    $index_html .= "<br>\n";
                    $index_html .= "<font color=\"#ffffff\">\n";
                    $index_html .= "$row->{picture_date}\n";
                    $index_html .= "</font>\n";
                    $index_html .= "<br>\n";
                }
                $index_html .= "<a href=\"$this_hfile_large\">";
                $index_html .= "<img src=\"$pfile_small\" border=\"0\">";
                $index_html .= "</a>\n";
                $i_cnt++;
                if ($i_cnt >= $i_per) {
                    $i_cnt = 0;
                }
            } else {

                # -- image file names
                $pfile         = $pic_root . '-raw.jpg';
                $pfile_small   = $pic_root . '-thumb.jpg';
                $pfile_large   = $pic_root . '-large.jpg';
                $pfile_larger  = $pic_root . '-larger.jpg';
                $pfile_largest = $pic_root . '-largest.jpg';

                # -- write the image files
                if (test_boolean($PROPS{'raw'})) {
                    write_file($pfile, $img_row->{raw});
                }
                if (test_boolean($PROPS{'thumb'})) {
                    write_file($pfile_small, $img_row->{sm});
                }
                if (test_boolean($PROPS{'large'})) {
                    write_file($pfile_large, $img_row->{lg});
                }
                if (test_boolean($PROPS{'larger'})) {
                    write_file($pfile_larger, $img_row->{lgr});
                }
                if (test_boolean($PROPS{'largest'})) {
                    write_file($pfile_largest, $img_row->{lgst});
                }
            }
        }
    }

    if (test_boolean($PROPS{'html'})) {
        # -- write last html file
        if (length($this_hfile) > 0) {
            write_html(
                $last_hfile,         $this_hfile,
                $pfile,              '',
                $this_hfile_large,   'Large',
                $this_hfile_larger,  "Larger",
                $this_hfile_largest, "Largest",
                $this_desc,          $this_pid
            );
            write_html(
                $last_hfile_large,   $this_hfile_large,
                $pfile_large,        '',
                $this_hfile,         'Raw',
                $this_hfile_larger,  "Larger",
                $this_hfile_largest, "Largest",
                $this_desc,          $this_pid
            );
            write_html(
                $last_hfile_larger,  $this_hfile_larger,
                $pfile_larger,       '',
                $this_hfile,         'Raw',
                $this_hfile_large,   "Large",
                $this_hfile_largest, "Largest",
                $this_desc,          $this_pid
            );
            write_html(
                $last_hfile_largest, $this_hfile_largest,
                $pfile_largest,      '',
                $this_hfile,         'Raw',
                $this_hfile_large,   "Large",
                $this_hfile_larger,  "Larger",
                $this_desc,          $this_pid
            );
        }

        # -- finish off the index
        $index_html .= "\n";
        $index_html .= "</td></tr></table>\n";
        $index_html .= "</div>\n";
        $index_html .= "\n";
        $index_html .= "</body>\n";
        $index_html .= "</html>\n";
        write_file($hfile_index,         $index_html);
        write_file('aaa' . $hfile_index, $index_html);
    }
}

##############################################################################
# Main Routine
##############################################################################

print ">>> ring-export\n";

# -- get options
GetOptions(
    'debug'        => \$opt_debug,
    'conf=s'       => \$opt_conf,
    'example'      => \$opt_example,
    'help'         => \$opt_help,
    'manual'       => \$opt_manual,
    'properties=s' => \$opt_properties
);

# help the poor souls out
if (!@ARGV || $ARGV[0] == 'help') {
    $opt_help = 1;
}
if ($opt_help) {
    pod2usage(-verbose => 0);
}
if ($opt_manual) {
    pod2usage(-verbose => 2);
}

# Set the picture range to process from the command line
my $pid_start = $ARGV[0];
if ($pid_start < 1) {
    pod2usage(-verbose => 0);
}
my $pid_end = $pid_start;
if ($ARGV[1]) {
    $pid_end = $ARGV[1];
}

# Get configuration settings and initial debugging if requested.
get_config($opt_conf);
if ($opt_debug) {
    $CONF->debug($opt_debug);
}
if ($CONF->debug) {
    dbg("Initialize timer.");
}

# Open up connections to the MySQL data
db_connect();

if (!-e $opt_properties) {
    msg('fatal', 'a properties file is required');
    pod2usage(-verbose => 0);
}

# -- read the properties

read_properties($opt_properties);
if ($opt_debug) {
    foreach my $a (sort keys %PROPS) {
        dbg("property $a = $PROPS{$a}");
    }
}

read_and_write($pid_start, $pid_end);

exit;

__END__

=head1 NAME

ring_export - export pictures to files

=head1 SYNOPSIS

ring-export --properties=filename [--debug] [--help] [--manual]

=head1 DESCRIPTION

Write a ring to disk for use on non-php web site.

=head1 OPTIONS AND ARGUMENTS

=over 4

=item --properties=filename

The filename that has properties.  Properties are in attribute=value
format.  Valid attributes are:

  selection = sql selection clause
  path = file-path used as prefix to all file created
  html = true|false
  raw = true|false    [ only used when html = false ]
  thumb = true|false  [ only used when html = false ]
  large = true|false  [ only used when html = false ]
  larger = true|false [ only used when html = false ]

=item --help

Displays help text.

=item --manual

Displays more complete help text.

=item --debug

Turns on debugging displays.

=back

=head1 AUTHOR

Bill MacAllister <bill@macallister.grass-valley.ca.us>

=cut
