package PhotoPub::Page;
require Exporter;
@ISA = qw(Exporter);
@EXPORT_OK = qw(&pagehtml);

use PhotoPub::Global qw($error);
use PhotoPub::Handlers qw(&handlephoto &parameterhandlephoto &listhandlephoto);
use PhotoPub::Utils qw(&slurp &untaint &uri_escape 
		       &handleparameters &includetag &excludetag
                       &makeabsolutepath &getdefault);
use PhotoPub::Ages qw(&updateagefromfiles);
use PhotoPub::Range qw(&dispahref &dispimg);
use PhotoPub::Annots qw(&getannot);
use PhotoPub::Display qw(&checkimageoptions);

use strict;

use HTML::Entities;

sub pagehtml {
  my ($options,$printheader,$printout)=@_;

  my $debug=exists $options->{'debug'} ? $options->{'debug'} : 0;

  if( $debug >= 1 ) {
    # Do the headers early, so we can output to the browser soon
    # Might lead to some of the headers being wrong though
    &$printheader();
    print "<pre>\n";
  }

  my $page=$options->{'page'};
  &$error(type=>'userinput',message=>'page not given')
    unless defined $page;

  my $pagetemplate=&handlephoto('pagetemplate',$page);
  &$error(type=>'userinput',message=>"Page $page not defined")
    unless defined $pagetemplate;

  my $template=slurp($pagetemplate)
    or &$error(type => 'config', message => "Couldn't open template file");

  my @params=&handleparameters($options,\$template);

  # Export $styleroot, the path of the stylesheet, into the template
  # This should go away if we can find a nice way to do relative style 
  # references here like in album.pl
  my $styleroot = substr( $page, 0, rindex( $page, '/' ) );
  $template=~s/\$styleroot/$styleroot/ieg;

  &updateagefromfiles($pagetemplate);

  $template=~s/\<img(.*?)picture\s+photo=(\S+)\s+(.*?)\>/&dispimg($1,$2,&getannot($2,'options'),$3,$styleroot)/gies;
  $template=~s/\<a(.*?)picture\s+photo=(\S+)\s+(.*?)\>/&dispahref($1,$2,&getannot($2,'options'),$3,$styleroot)/gies;
  
  if( $debug == 0 ) {
    # We now know everything for the headers
    &$printheader();
  }

  &$printout($template);
}
