# Album Plugin: images/annotate-medium
# For info: 'album -plugin_info images/annotate-medium'
# For usage:  'album -plugin_usage images/annotate-medium'
use strict;		# Not required, but recommended

my $DESCRIPTION = << 'DESCRIPTION';
Annotates medium images with a string of text such as a copyright tag.
Copyright idea credit:  Joe Botha

DESCRIPTION

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

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

	# Setup the hooks
 	album::hook($opt, 'do_album_top', \&sanity);
 	album::hook($opt, 'medium', \&medium);
	album::add_option(1,'text',$album::OPTION_STR, usage=>"Text to annotate on image");
	album::add_option(1,'first_time',$album::OPTION_BOOL, default=>0, one_time=>1, usage=>"Force annotation of medium images even if they're already generated");
	album::add_option(1,'fg',$album::OPTION_STR, default=>'white', usage=>"Foreground (text) color");
	album::add_option(1,'bg',$album::OPTION_STR, default=>'black', usage=>"Background (border) color");

	return $ret;
}

my $PLUGNAME;
sub sanity {
	my ($opt, $hook) = @_;
	$PLUGNAME = album::curr_plugin($opt);
	album::fatal($opt,"Plugin $PLUGNAME requires album -medium option\n") unless $opt->{medium};
	album::perror($opt,"Plugin $PLUGNAME expects album -just_medium option\n\tOnly medium images will be annotated\n")
		unless $opt->{just_medium};
	album::fatal($opt,"Plugin $PLUGNAME requires -text option\n")
		unless album::option($opt,'text');
	0;
}

sub medium {
	my ($opt, $hook,  $dir, $obj, $file, $full_path) = @_;

	# Deal with changed options
	unlink($obj->{medium}{path})
		if album::option_changed($opt,'text')
			|| album::option_changed($opt,'fg')
			|| album::option_changed($opt,'bg');

	# If the image already exists, don't bother,
	return undef if -f $obj->{medium}{path}
		&& !album::option($opt,'first_time')
		&& !album::option_changed($opt,'medium');
## BUG!  What if medium is regen (because of full image change?)

	# Actually make the medium
	album::medium($opt,$dir,$obj);

	my $text = album::option($opt,'text');
	my $fg = album::option($opt,'fg');
	my $bg = album::option($opt,'bg');
	system('convert',$obj->{medium}{path},'-bordercolor',$bg,'-background',$bg,
		'-border','2','-gravity','SouthEast','-splice','0x12','-fill',$fg,
		'-annotate','0',$text,$obj->{medium}{path});
	album::perror($opt,"[$PLUGNAME] Trouble with convert [$obj->{medium}{path}]\n")
		if $?;

	# Need to erase the cached size of the image
	undef $obj->{medium}{x};
	undef $obj->{medium}{y};

	# Still return undef, we haven't actually generated the thumbnail.
	return $obj->{medium}{path};
}


# Plugins always end with:
1;
