# Simple Photo Gallery
# (c) 2003--2012 Martin Mares <mj@ucw.cz>

package UCW::Gallery;

use strict;
use warnings;

use Storable;

BEGIN {
	# Standard Perl module stuff
	use Exporter();
	our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
	$VERSION = 1.00;
	@ISA = qw(Exporter);
	@EXPORT = qw(&SetOptions);
	%EXPORT_TAGS = ();
	@EXPORT_OK = qw(%CF);
}

our %CF;

BEGIN { %CF = (
	# Directories
	OrigDir => '.',			# Original images
	PhotoDir => 'photo',		# Scaled-down photos for web
	CacheDir => 'cache',		# Cache with meta-data and thumbnails
	ThemeDir => 'gal',		# Themes

	# URL prefixes
	PhotoUrlPrefix => 'photo/',
	ThumbUrlPrefix => 'thumb/',
	ThemeUrlPrefix => 'gal/',

	# Processing machinery settings
	ScanDefaultTransform => 's',
	PhotoMaxWidth => 1024,
	PhotoMaxHeight => 1024,
	ThumbFormats => {},		# Set up by themes

	# HTML output settings
	Title => 'An Unnamed Gallery',
	HeadExtras => "",
	TopExtras => "",
	BotExtras => "",
	ParentURL => '../',
	BackURL => "",
	FwdURL => "",
	ImageSubpages => 1,
); }

sub LoadConfig() {
	my $cfg = "./gallery.cf";
	unless (defined do $cfg) {
		if ($@) {
			die "Error parsing $cfg: $@";
		} elsif ($!) {
			die "Cannot load $cfg: $!\n";
		} else {
			die "Cannot load $cfg, check that it returns true\n";
		}
	}
}

sub SetOptions(@) {
	while (my $o = shift @_) {
		my $v = shift @_;
		$CF{$o} = $v;
		if ($o eq "Theme") {
			require $CF{'ThemeDir'} . "/$v/theme.pm";
			UCW::Gallery::Theme::Init($CF{'ThemeUrlPrefix'} . $v);
		}
	}
}

sub RequireThumbnails($$) {
	my ($w, $h) = @_;
	my $fmt = "${w}x${h}";
	$CF{'ThumbFormats'}->{$fmt} = 1;
}

sub WriteList($$) {
	my ($file, $images) = @_;
	open LIST, '>', "$file.new" or die "Cannot create $file.new: $!\n";
	print LIST "# Image\tID\tRotate\tXform\tTitle\n";
	for my $i (@$images) {
		print LIST join("\t",
			$i->{file},
			$i->{id},
			$i->{orientation},
			$i->{xfrm},
			($i->{title} eq '' ? '-' : $i->{title}),
		), "\n";
	}
	close LIST;
	rename "$file.new", $file or die "Cannot rename $file.new to $file: $!\n";
}

sub ReadList($) {
	my ($file) = @_;
	my @images = ();
	open LIST, '<', $file or return;
	while (<LIST>) {
		chomp;
		/^$/ and next;
		/^#/ and next;
		my $i = {};
		($i->{file}, $i->{id}, $i->{orientation}, $i->{xfrm}, $i->{title}) = split /\t/;
		if ($i->{title} eq '-') { $i->{title} = ""; }
		push @images, $i;
	}
	close LIST;
	return \@images;
}

sub WriteMeta($$) {
	my ($file, $meta) = @_;
	open META, '>', "$file.new" or die "Cannot create $file.new: $!\n";
	Storable::nstore_fd($meta, \*META);
	close META;
	rename "$file.new", $file or die "Cannot rename $file.new to $file: $!\n";
}

sub ReadMeta($) {
	my ($file) = @_;
	open META, '<', $file or die "Cannot read $file: $!\n";
	my $meta = Storable::fd_retrieve(\*META) or die "Cannot parse $file\n";
	close META;
	return $meta;
}

1;
