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

package UCW::Gallery;

use strict;
use warnings;

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;
our $th;

BEGIN {
	$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'} = '.',

	$CF{'ScanDefaultTransform'} = 'n';
	$CF{'OrigDir'} = '.';
	$CF{'PhotoDir'} = 'photo';
	$CF{'CacheDir'} = "cache",
}

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

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;
}

1;
