# Album Plugin:	utils/capindex
# For info:	'album -plugin_info utils/capindex'
# For usage:	'album -plugin_usage utils/capindex'
# Replaces the album standalone tool 'caption_index'
use strict;

my $DESC = <<DESC;
Creates an HTML captioned index of all the photos in a hierarchy of albums.
DESC

sub start_plugin {
  my ($opt,$plugin,$path) = @_;

  album::add_option(1,'index',album::OPTION_STR, default=>'capindex.html', args=>'<file>', usage=>"Output file for album index plugin");

  album::hook($opt,'do_album_top', \&header);
  album::hook($opt,'end_album_top', \&footer);
  album::hook($opt,'write_index', \&write_index);

  # We don't need album to do this stuff:
  album::hook($opt,'write_image_pages', sub { return 1; });
  album::hook($opt,'thumbnail', sub { return 1; });
  album::hook($opt,'medium', sub { return 1; });
  album::hook($opt,'get_xy', sub { return (1,1); });
  album::hook($opt,'get_exif_info', sub { return {}; });

  # Don't save confs (this plugin is a one-time thing)
  $opt->{save_conf} = 0;

  # Hashes are unneded
  $opt->{hashes} = 0;

  return {
    author => 'David Ljung Madison',
    href => 'http://MarginalHacks.com/',
    version => '1.0',
    description => $DESC,
  };
}

sub header {
  my ($opt,$data,$hook, $dir, $path) = @_;

# TODO: What's the path from???
  my $index = album::option($opt,'index');
  open(INDEX,">$dir/$index") || album::usage($opt,"Can't write plugin index [$dir/index]");

  # Header
  print INDEX "Photo album index for $path:\n<p><hr><p>\n";

	return 0;	# Don't terminate do_album_top
}

sub footer {
  my ($opt,$data,$hook, $dir) = @_;

  print INDEX "<p><hr><p>\n";
  print INDEX album::credit($opt);
  close INDEX;
}

sub write_index {
  my ($opt, $data,$hook, $dir, $album) = @_;

  # We're in the top album directory, get the path from there.
  # (This is just $album without the first dir. component)
  my @path = @{$data->{dir_pieces}};
  shift @path;
  my $path = join('/',@path) || '.';

  my $qpath = album::url_quote($opt,$path);
  print INDEX "<a href=$qpath>$album</a>\n<ul>\n";

  # All the images
  foreach my $pic ( @{$data->{pics}} ) {
    my $obj = $data->{obj}{$pic};

    my $url = $obj->{URL}{album_page}{image};
    if ($path ne '.') {
      $url =~ s/^'(.*)'$/$1/g;
      $qpath =~ s/^'(.*)'$/$1/g;
      $url = "'$qpath/$url'";
    }

    print INDEX "  <a href=$url>$obj->{name}</a> ";
# TODO: This needs to output to INDEX!
    album::caption($obj);
    print INDEX "<br>\n";
  }

  print INDEX "</ul>\n";
}

# Plugins always end with:
1;
