# 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 {
	# FIXME: Check config
	$CF{'Title'} = 'An Unnamed Gallery',
	$CF{'HeadExtras'} = "",
	$CF{'TopExtras'} = "",
	$CF{'BotExtras'} = "",
	$CF{'ParentURL'} = '../',
	$CF{'BackURL'} = "",
	$CF{'FwdURL'} = "",
	$CF{'ImageSubpages'} = 1,
	$CF{'AllowArchives'} = 1,
	$CF{'PhotoUrlPrefix'} = "",
	$CF{'ThumbUrlPrefix'} = "",
	$CF{'MetaDataDir'} = '.',
	$CF{'PhotoDir'} = '.',
	# FIXME: Who sets GalDir?

	$CF{'ScanDefaultTransform'} = 's';
	$CF{'OrigDir'} = '.';
	$CF{'PhotoDir'} = 'photo';
	$CF{'CacheDir'} = 'cache',
	$CF{'PhotoMaxWidth'} = 1024,
	$CF{'PhotoMaxHeight'} = 1024,
	$CF{'ThumbFormats'} = {},
}

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{"GalDir"} . "/$v/theme.pm";
			UCW::Gallery::Theme::Init($CF{"GalURL"} . "/$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;
