package PhotoPub::Embed;
require Exporter;
@ISA = qw(Exporter);
@EXPORT_OK = qw(&embedhtml);

use PhotoPub::Global qw($error);
use PhotoPub::Handlers qw(&handlephoto &parameterhandlephoto &listhandlephoto);
use PhotoPub::Utils qw(&slurp &doifcount &untaint &uri_escape 
		       &handleparameters &includetag &excludetag
                       &parserange &makeabsolutepath &getdefault);
use PhotoPub::Images qw(&picfile &picrange &canonicalname);
use PhotoPub::Cache qw(&imagesize);
use PhotoPub::Annots qw(&getannot);
use PhotoPub::Ages qw(&updateagefromfiles);
use PhotoPub::Range qw(&dispahref &dispembedahref &dispimg &dispinfo);
use PhotoPub::Display qw(&checkimageoptions);

use strict;

use HTML::Entities;

sub embedhtml {
  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 $photo=$options->{'photo'}
    or &$error(type=>'userinput',message=>'Must give a photo!');
  &makeabsolutepath(\$photo);
  
  my $style=$options->{'style'};
  $style=&getdefault('embedstyle') unless defined $style;
  &$error(type=>'userinput',message=>'style not given and no default defined')
    unless defined $style;

  my $embedtemplate=&handlephoto('embedtemplate',$style);
  &$error(type=>'userinput',message=>"Embedding style $style not defined")
    unless defined $embedtemplate;

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

  my $photooptions=&checkimageoptions($options);

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

  if($template=~s/\<userange lowest\>//i) {
    my $album=$options->{'album'};
    &$error(type => 'userinput',
	    message => "album must be specified for embed template $style")
      unless defined $album;

    my $items=&listhandlephoto('album',$album);
    my $wantedphoto=&canonicalname($photo);
    my $bestlevel=-1;
    my $besttitle="";
    my $bestrange="";
    foreach my $item (@$items) {
      my $choosethis = sub {
	$bestlevel=$item->{'level'};
	$besttitle=$item->{'description'};
	$bestrange=$item->{'range'};
      };
      if($item->{'type'} eq 'group' && $item->{'level'} > $bestlevel) {
	&parserange($item->{'range'},&getdefault('path'),
		    sub {
		      my ($foundpath,$foundnum)=@_;
		      my $foundphoto=$foundpath.$foundnum;
		      if(&canonicalname($foundphoto) eq $wantedphoto) {
			&$choosethis();
			return 0;
		      }
		      return 1;
		    });
      }
    }
    if($bestlevel==-1) {
      &$error(type=>'userinput',message=>'photo is not listed in a range');
    }
    $template=~s/\$rangetitle/$besttitle/gi;
    $template=~s/\$range/$bestrange/gi;
  }

  # 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( $style, 0, rindex( $style, '/' ) );
  $template=~s/\$styleroot/$styleroot/ieg;

  &updateagefromfiles($embedtemplate);

  $template=~s/\$photo/&encode_entities(&canonicalname($photo))/ieg;

  my $descr=getannot($photo,'description');
  if(defined $descr) {
    &includetag('ifdescr',\$template);
    &excludetag('ifnodescr',\$template);
    # allowhtml setting will already have caused $descr to be HTML escaped 
    # if necessary
    $template=~s/\$description/$descr/ig;
  } else {
    &excludetag('ifdescr',\$template);
    &includetag('ifnodescr',\$template);
    $template=~s/\$description//ig;
  }

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

  &$printout($template);
}
