# Pick directory thumbnail using captions.txt
sub start_plugin {
	my ($opt) = @_;

	album::hook($opt,'dir_thumb',\&dir_thumb);
  album::add_option(1, 'caption', album::OPTION_STR, default=>'dir_thumb',
                    usage=>'The caption string to look for');

	return {
		author => 'David Madison',
		href => 'http://MarginalHacks.com/',
		version => '1.0',
		description => <<'DESC'};
Pick directory thumbnail based on captions.txt file.

In captions.txt you can add a "caption" line:

dir_thumb	<file>

Where <file> is the image you want to use to select the directory thumbnail.
You can also specify a directory (relative paths only), in that case we'll
recursively look there for the thumbnail, using album dir_thumb behavior
(or possibly this plugin again)

Based on ideas from Dave Hansen <http://www.sr71.net/>
DESC
}

sub search_dirs_for_thumb
{
	my ($opt,$child,$child_data,@child_dirs_to_search) = @_;

	foreach my $search_child ( @child_dirs_to_search ) {
		my ($tn_path,$url,$full_path,$img) = album::dir_info($opt,$child_data,$search_child);
		#dprint "searching '$search_child' full_path: '$full_path' tn_path:'$tn_path' img:'$img'\n";
		return ($tn_path,"$child/$url",$full_path,$img) if $img;
	}
	return undef;
}


sub dir_thumb {
	my ($opt,$data,$hookname, $child, $child_data, @images) = @_;

	my $capname = album::option($opt,'caption');

	my $dir = $data->{paths}{dir};
	my $child_path = "$dir/$child";

	# BUG: If the captions setting changes in a sub-album, we won't notice.
	#      That's pretty minimal.

	my $caps = album::read_captions($opt,$child_path);
	my $thumb = $caps->{$capname}{name};
#print STDERR "T: $thumb [$child_path]\n";

	if ($thumb) {
		# somebody explicitly specified a thumbnail

		my $path = "$child_path/$thumb";

		# An image
		return ($child_path,$child,$path,$thumb) if -f $path;

		# Allow for absolute or relative path (which could lead us
		# outside the album path!  Hope that works
#print "DIR: $path\n" if -d $path;
		return album::dir_info($opt, $child_data, $thumb) if -d $path;
	}
	
	# Nobody specified one, but there's an image here.
	# Album's default is to use that, we'll copy that behavior if there is one.
	return ($child_path,$child,"$child_path/$images[0]",$images[0])
		if defined $images[0];
	
	# Otherwise descend directories recursively
	# (This will actually do a funky plugin recursive loop, but it'll work)
	return search_dirs_for_thumb($opt, $child, $child_data, @{$child_data->{dirs}});
}

# Plugins always end with
1;

