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

package UCW::Gallery::Web;

use strict;
use warnings;

use UCW::Gallery;
use UCW::CGI;
use File::Spec;

my $show_img;

my %args = (
	'i'	=> { 'var' => \$show_img, 'check' => '\d+' },
);

sub error($) {
	print "<p style='color:red'>Bad luck, the script is broken. Sorry.\n<p>$_[0]\n";
	print "</body></html>\n";
}

sub get($$) {
	my ($self, $key) = @_;
	return $self->{gal}->get($key);
}

sub html_top($) {
	my ($self) = @_;
	my $title = UCW::CGI::html_escape($self->get('Title'));
	my $hextras = $self->get('WebHeadExtras');
	my $textras = $self->get('WebTopExtras');
	my $theme_hextras = $self->theme_head_extras;
	print <<EOF ;
Content-Type: text/html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head>
$hextras
$theme_hextras
<title>$title</title>
</head><body>
$textras
EOF
	$UCW::CGI::error_hook = \&error;
}

sub html_bot($) {
	my ($self) = @_;
	print $self->get('WebBotExtras'), "\n</body></html>\n";
}

sub show_img($) {
	my ($self) = @_;

	if ($show_img < 1 || $show_img > $self->{num_photos}) {
		print "Status: 404\n";
		$self->html_top;
		print "<h1>No such photo</h1>\n";
		$self->html_bot;
		return;
	}

	my $meta = $self->{meta};
	my $id = $meta->{sequence}->[$show_img-1];
	my $m = $meta->{photo}->{$id} or die;
	$self->html_top;

	$self->show_links(($show_img > 1 ? ("?i=".($show_img-1)) : ""),
			  "?",
			  ($show_img < $self->{num_photos} ? ("?i=".($show_img+1)) : ""));

	my $t = UCW::CGI::html_escape($m->{title});
	my $w = $m->{w};
	my $h = $m->{h};
	print "<h1>$t</h1>\n" if $t ne "";
	my $img = $self->get('PhotoUrlPrefix') . $id . '.jpg';
	print "<p class=large><img src='$img' width=$w height=$h alt='$t'>\n";

	$self->html_bot;
}

sub show_list($) {
	my ($self) = @_;
	$self->html_top;

	$self->show_links($self->get('BackURL'), $self->get('ParentURL'), $self->get('FwdURL'));
	print "<h1>", $self->get('Title'), "</h1>\n";
	my $subtitle = $self->get('SubTitle');
	print "<h2>$subtitle</h2>\n" if $subtitle ne "";

	my $meta = $self->{meta};
	for my $idx (1..$self->{num_photos}) {
		my $id = $meta->{sequence}->[$idx-1];
		my $click_url;
		if ($self->get('WebImageSubpages')) {
			$click_url = "?i=$idx";
		} else {
			$click_url = $self->get('PhotoUrlPrefix') . "$id.jpg";
		}
		$self->show_thumb($meta, $id, $click_url);
	}

	$self->html_bot();
}

sub dispatch($) {
	my ($self) = @_;
	UCW::CGI::parse_args(\%args);
	$self->{meta} = UCW::Gallery::ReadMeta(File::Spec->catfile($self->get('CacheDir'), 'cache.meta'));
	$self->{num_photos} = scalar @{$self->{meta}->{sequence}};

	if ($show_img ne "") {
		$self->show_img;
	} else {
		$self->show_list;
	}
}

sub attach($$) {
	my ($class, $gal) = @_;
	my $self = { gal => $gal };
	$gal->def(
		WebFE => $self,
		WebHeadExtras => "",
		WebTopExtras => "",
		WebBotExtras => "",
		WebThemeCSS => undef,
		WebImageSubpages => 1,
	);
	bless $self, $class;
	return $self;
}

42;
