# Simple Photo Gallery: Thumbnail Generator
# (c) 2003--2004 Martin Mares <mj@ucw.cz>

package Gallery::Generator;

use strict;
use warnings;

use Image::Magick;
use IO::Handle;

BEGIN { import Gallery qw(%CF); }

sub new() { return bless {}; }

sub Start($) {
	print "Generating thumbnails...\n"; STDOUT->autoflush(1);
	my $notes = $CF{'MetaDataDir'} . "/notes";
	open NOTES, ">$notes" or die "Unable to write to notes ($notes): $!";
}

sub Finish($) {
	close NOTES;
	print "Done.\n";
}

sub RawHTML($$) { }

sub img($$$) {
	my ($this, $orig, $annot) = @_;
	my ($base, $ext) = ($orig =~ /^(.*)\.([^.]+)$/) or die "Unable to dissect name $orig";
	print "$base: ";
	my $p = new Image::Magick;
	my $e;
	my $img = $CF{"PhotoDir"} . $orig;
	$e = $p->Read($img) and die "Error reading $img: $e";
	my ($wo, $ho) = $p->Get('width', 'height');
	my ($w, $h) = ($wo, $ho);
	print "${w}x${h}";
	$p->Strip;
	if ($w > $CF{"ThumbW"}) {
		my $s = $CF{"ThumbW"} / $w;
		$w = $w * $s;
		$h = $h * $s;
	}
	if ($h > $CF{"ThumbH"}) {
		my $s = $CF{"ThumbH"} / $h;
		$w = $w * $s;
		$h = $h * $s;
	}
	$w = int($w);
	$h = int($h);
	print " -> ${w}x${h} ";
	$p->Resize(width=>$w, height=>$h);
	my $thumb = $CF{"ThumbDir"} . "$base-thumb.jpg";
	$e = $p->Write($thumb) and die "Unable to write $thumb: $e";
	print NOTES "$base $w $h $wo $ho\n";
	print "OK\n";
}

1;
