#!/usr/bin/perl
##################################################################################################################################

my($mcf,$pdf,$n,$p0,$p1,$mrg,$dpi,$dobkg,$frm)=(undef,undef,0,0,9999,0,100,1,none); 

my($RES,$TTF,$TMP)=("./Pixum Fotowelt/Resources/photofun/backgrounds/",
                    "./Pixum Fotowelt/Resources/photofun/fonts/","./mcf2pdf.tmp/");
my %FRAME=(
 'random'     => "imageborder -s 50 -b 1 -m white -p 30 -r white -t 1 -e random",
 'dither'     => "imageborder -s 50 -b 0 -m white -p 30 -r white -t 1 -e dither",
 'polaroid'   => "convert -border  5%   -bordercolor white -gravity south -splice 0x20%",
 'gray'       => "convert -border 50x50 -bordercolor lightgray",
 'ivory'      => "convert -border 50x50 -bordercolor ivory",
 'white'      => "convert -border 50x50 -bordercolor white",
 'stamp'      => "postagestamp -B olive -H white -b 30 -d 30",
 'curve'      => 'bordereffects -s 20 -c 8 -p 20 -b white',
 'bevel'      => 'bevelborder -s 20 -m split -p 25',
 'cartoon'    => "cartoon -p 60 -e 4 -n 6",
 'frame'      => "picframe -d 10 -m 10",
 'watercolor' => "watercolor",
 'vintage'    => "vintage3",
 'none'       => "cp",
);

my $FRAMES=join '|',keys %FRAME;

foreach(@ARGV)
{
  $mcf="$1.mcf"       if(/^(.*)\.mcf$/);
  $pdf="$1.pdf"       if(/^(.*)\.pdf$/);

 ($p0,$p1)=($1-1,$2)  if(/^-p(\d+)-(\d+)$/);
 ($p0,$p1)=($1-1,$1)  if(/^-p(\d+)$/);

  $dpi=$1             if(/^-dpi(\d+)$/);

  $mrg=$1*5           if(/^-m(\d+)$/);

  $frm=$1             if(/^-($FRAMES)$/);

  $dobkg=0            if(/^-nobackground$/);

  $force++            if(/^-force$/);

  $wkhtml++           if(/^-wkhtml$/);

  $book++             if(/^-book$/);
}
  $pdf="$1 - $dpi$frm.pdf" if($mcf=~/^(.*)\.mcf$/ and !$pdf); exit -1 unless($mcf and $pdf);

my $xml=qx(iconv -c -t ISO-8859-15 "$mcf"); $TMP.="$dpi$frm";   qx{mkdir -p "$TMP"};

my $DIR=$1 if($xml=~/<fotobook [^>]*imagedir="(.*?)"/);       exit -2 unless($DIR);

my $TAGS=join '|',qw( page bundlesize area position image cutout designElementIDs body span style br p );

   $xml=~s{<(/?($TAGS)[^>]*)>}{«$1»}gs;
   $xml=~s{<\w[^>]*>}{}gs;
   $xml=~s{<\/\w[^>]*>}{}gs;
   $xml=~s{"\d+\.\d+e-\d+"}{"0"}gs;
   $xml=~s{\n\s+}{\n}gs;
   $xml=~s{\n+}{\n}gs;
   $xml=~s{«}{<}gs;
   $xml=~s{»}{>}gs;

 # print "$xml\n\n";

my($A4W,$A4H,$WW,$HH,$MM,$PI,@pg,%bg)=(595,842,595,842,2100/595,3.14159265358979); 

print "$frm => $FRAME{$frm}\n";

use PDF::API2;

my $pdf_= PDF::API2->new(-file => "~$pdf");
 
print "OPEN $pdf\n";

my $f1 = $pdf_->corefont('Helvetica-Bold');
my $f2 = $pdf_->corefont('Georgia-Italic', -encode=>'latin1');
my $f3 = $pdf_->ttfont("$TTF/IndieFlowerCEWE-Regular.ttf");

foreach $page (split /<page /,$xml)
{
 ($HH,$WW)=($1/$MM,$2/$MM/2) if($page=~/<bundlesize height="(\d+)" width="(\d+)"/);

  my $bkg=$1                 if($page=~/<designElementIDs background="(\d+)"/);                

  my $pnr=$1+2               if($page=~/pagenr="(\d+)"/);   next if($page!~/type="(fullcover|normalpage|emptypage)"/);

     $pnr=0                  if($page=~/type="fullcover"/);
     $pnr=2                  if($page=~/type="emptypage"/);

  foreach $area (split /<area /,$page)
  {
    my $pos=$1    if($area=~/<position ([^>]*)>/);

                     $area=~       s/font-weight:[0-4]\d+;/font-weight:normal;/g;
                     $area=~       s/font-weight:[5-9]\d+;/font-weight:bold;/g;

    my $ft=$1     if($area=~        /font-family:'([^']+)'/);
       $ft=$1     if($area=~/<span .*font-family:'([^']+)'/);
    my $fs=$1     if($area=~        /font-size:(\d+)pt/);
       $fs=$1     if($area=~/<span .*font-size:(\d+)pt/);
    my $fc=$1     if($area=~        /color:#([a-f\d]+);/);
       $fc=$1     if($area=~/<span .*color:#([a-f\d]+);/); $fc||='000000';

    my $img=$1    if($area=~/areatype="imagearea".*<image .*filename="safecontainer:\/(.*\.jpe?g)"/s);  
    my $cnv=$1    if($area=~/areatype="imagearea".*<image .*filename="safecontainer:\/(.*)\.(gif|png)"/s);  
    my $ppt=$1    if($area=~/areatype="imagearea".*<image .*passepartoutDesignElementId="(\d+)"/s);

    my $txt=$1    if($area=~/areatype="textarea".*<\/style>(.*?)\]\]/s); $txt=~s/<br \/>/\n/g;
                                                                         $txt=~s/<\/p>/\n/g;
                                                                         $txt=~s/<[^>]*>//g;
                                                                         $txt=~s/&amp;/&/g;
                                                                         $txt=~s/&quot;/"/g;
                                                                         $txt=~s/\s*$//sg;
    my $x=$1/$MM  if($pos=~/left="(\d+)/);
    my $y=$1/$MM  if($pos=~/top="(\d+)/);
    my $h=$1/$MM  if($pos=~/height="(\d+)/);
    my $w=$1/$MM  if($pos=~/width="(\d+)/);
    my $r=$1      if($pos=~/rotation="(-?\d+)/); $r=360-$r if($r);
    my $z=$1      if($pos=~/zposition="(\d+)/);

    my $cut=$1    if($area=~/<cutout ([^>]*)>/);

    my $x0=$1/$MM if($cut=~/left="(-\d+)/);
    my $y0=$1/$MM if($cut=~/top="(-\d+)/);
    my $sc=$1     if($cut=~/scale="(\d+(\.\d+)?)/);
     
    qx{cd "$DIR"; convert "$cnv.gif" "$cnv.jpg"},$img="$cnv.jpg" if($cnv and -r "$DIR/$cnv.gif");
    qx{cd "$DIR"; convert "$cnv.png" "$cnv.jpg"},$img="$cnv.jpg" if($cnv and -r "$DIR/$cnv.png");

    my  $p=($x<$WW)? $pnr:$pnr+1; next if($p<$p0);
                                  next if($p>$p1);
        $x=($x<$WW)? $x-$mrg/$MM:
                     $x+$mrg/$MM-$WW;
 
           # $pnr  $z typ  $x  $y  $w  $h  $r $x0 $y0   $sc $txt/$img
    printf(qq{%4d %4d txt %4d %4d %4d %4d %4d %4d %6s %4.2f "%s"\n},$p,$z,$x,$y,$w,$h,$r,$fs,$fc,$sc,$txt) if($txt);  

    unless(defined $pg[$p])
    {
      foreach("$RES","$RES/einfarbige","$RES/multicolor","$RES/spotcolor")
      {
       qx{cp           "$_/$bkg.jpg"  "$TMP/$bkg.jpg" 2>/dev/null}   if(!-r "$TMP/$bkg.jpg" and -r "$_/$bkg.jpg");
       qx{ffmpeg -y -i "$_/$bkg.webp" "$TMP/$bkg.jpg" 2>/dev/null}   if(!-r "$TMP/$bkg.jpg" and -r "$_/$bkg.webp");
      }

      $pg[$p] = $pdf_->page; $n++;

      $gf[$p] = $pg[$p]->gfx();
      $tx[$p] = $pg[$p]->text(); ($A4W,$A4H)=($A4H,$A4W) if($WW>$HH and $A4W<$A4H);
                $pg[$p]->mediabox($A4W,$A4H);

      $gf[$p]->scale($A4W/$WW,$A4H/$HH);
      $tx[$p]->scale($A4W/$WW,$A4H/$HH);

      $tx[$p]->font($f3,12);
      $tx[$p]->fillcolor(black);
      $tx[$p]->translate(($p%2)?  $WW-$tx[$p]->advancewidth($p-1)-15:15,10);

      $tx[$p]->text($p-2) if($dobkg+1 and $p>2);

      do
      {
        my $image=$pdf_->image_jpeg("$TMP/$bkg.jpg");

        $gf[$p]->image($image,0,0,$WW,$HH);
      }                                                    if($bkg and  -r "$TMP/$bkg.jpg" and $dobkg);
    }
                                                                                     next unless($pos);

    if($wkhtml and $txt and $area=~/areatype="textarea".*<!\[CDATA\[(.*?)\]\]/s)
    {
     use Digest::MD5 qw(md5_hex);          my $htm=$1;        $img=sprintf('txt-%s.png',md5_hex($1));

     do
     {
       open HTML,">$TMP/$$.html"; print HTML "$htm\n"; close HTML;

       my $BORDER="mogrify -trim -border x10 -bordercolor matte";

                     my $wh=sprintf("--transparent --width %d --height %d --zoom 2",3*$w,3*$h);

       qx{wkhtmltoimage $wh "$TMP/$$.html" "$TMP/$img" 2>/dev/null;
          $BORDER                          "$TMP/$img";
          rm                "$TMP/$$.html"};
     }                                                     if($htm and !-r "$TMP/$img" || $force);
    }

           # $pnr  $z typ  $x  $y  $w  $h  $r $x0 $y0   $sc $txt/$img
    printf(qq{%4d %4d img %4d %4d %4d %4d %4d %5d %5d %4.2f "%s"\n},$p,$z,$x,$y,$w,$h,$r,$x0,$y0,$sc,$img) if($img);  

    my $CROP   = ($sc)? sprintf("convert -auto-orient -crop %dx%d+%d+%d",map $_*$MM/$sc,($w,$h,-$x0,-$y0)):"cp";  $sc=254.0/$dpi if($dpi);
    my $RESIZE = ($sc)? sprintf("mogrify            -resize %dx%d",      map $_*$MM/$sc,($w,$h))          :"ls";

           my $frm_=($ppt==74202)? 'polaroid':($txt)? 'none':$frm;

    qx{$CROP "$DIR/$img" "$TMP/$$.jpg"; 
       $RESIZE           "$TMP/$$.jpg";
       $FRAME{$frm_}     "$TMP/$$.jpg" "$TMP/$img";
       $RESIZE                         "$TMP/$img";
       rm -f             "$TMP/$$.jpg";}                   if($img and -r "$DIR/$img" and !-r "$TMP/$img" || $force);

    do
    {
      my $image=($img=~/png$/)? $pdf_->image_png ("$TMP/$img")
                              : $pdf_->image_jpeg("$TMP/$img");

                                  my($dx,$dy)=($w/2-cos($r*$PI/180)*$w/2,
                                                   +cos($r*$PI/180)*$h/2);
                          $x=($WW-$w)/2 if($p==1);
      $gf[$p]->save;
      $gf[$p]->translate( $x+$dx, $HH-$y-$dy); $gf[$p]->rotate($r) if($r);
      $gf[$p]->translate(-$x-$dx,-$HH+$y+$dy);

      $gf[$p]->image($image,$x,$HH-$y-$h,$w,$h);              $txt=undef;
      $gf[$p]->restore;
    }                                                      if($img && $gf[$p] && -r "$TMP/$img");

    do
    {
                                  $y/=2,$fs*=1.25 if($fs<16);
                 my @font=($p==1)? ($f2,$fs/ 1.3)
                                 : ($f3,$fs/ 1.3);
      $tx[$p]->font(@font);
      $tx[$p]->fillcolor(black);     $w=$tx[$p]->advancewidth($txt),$x=($WW-$w)/2,$r=0 if($p==1);

    # printf("HH=%d, h=%d, y=%d, dy=%d HH-y=%d\n",$HH,$h/$MM,$y/$MM,$dy/$MM,$HH-($y-$dy)/$MM); $y=0;

      $tx[$p]->lead($font[1]*1.2);       my($dx,$dy)=($w/2-cos($r*$PI/180)*$w/2,
                                                          +sin($r*$PI/180)*$w/2.7
                                                          +cos($r*$PI/180)*$h/4+$fs/$MM);
      $tx[$p]->transform(-translate =>  [$x+$dx,$HH-$y-$dy], 
                         -rotate => $r);

      $tx[$p]->text($tx[$p]->section($txt,$w,$h));
    }                                                      if($txt && $tx[$p]);
  }
}
       $n-=2;
print "$n -> ";

my $last;
   $last=$pdf_->page,$last->mediabox($A4W,$A4H),$n++ if($n%2);
   $last=$pdf_->page,$last->mediabox($A4W,$A4H),$n++ if($n%4 and $book);
   $last=$pdf_->page,$last->mediabox($A4W,$A4H),$n++ if($n%4 and $book);

print "$n\n";

$pdf_->save();         my $rot=($A4W<$A4H)? '':'west';

qx{pdftk  "~$pdf" cat 2-$n$rot 1$rot output "$pdf"; pdfbook --short-edge "$pdf" 2>/dev/null} if($book);
qx{pdftk  "~$pdf" cat 2-$n     1     output "$pdf"; rm                  "~$pdf" };

print "\n";
exit;
##################################################################################################################################

