#!/usr/bin/perl

#use utf8;
use strict;
use CGI;
use PDF::Create;
use POSIX qw(
    floor
);

use Opals::Context;
use Opals::Template qw(
    tmpl_read
    tmpl_write
);
use Opals::Search qw(
    srch_searchRecord
);
use Opals::Marc21 qw(
    mc21_parseRecord
);
use constant    X_PAGE        =>  612;
use constant    X_LEFT_MARGIN =>  25;
use constant    Y_PAGE        =>  792;
use constant    X_TABLE       =>  558;
use constant    ROW_HEIGHT    =>   18;
use constant    COL1_WIDTH    =>   50;
use constant    COL2_WIDTH    =>   20;


my $dbh = Opals::Context->dbh();
END { $dbh->disconnect(); }

my $cgi = CGI->new;
my $input = $cgi->Vars();
my $rid = $input->{'rid'};
#----------------------------------------------------------------------------------------------------
my $mypdf=`/bin/mktemp`;
  my $pdf = new PDF::Create('filename' => $mypdf,
                              'Version'  => 1.2,
                              'PageMode' => 'UseOutlines',
                              'Title'    => 'My title',
                         );
    my $root = $pdf->new_page('MediaBox' => [ 0, 0, X_PAGE,Y_PAGE ]);
# Prepare 2 fonts
    my $f1 = $pdf->font('Subtype'  => 'Type1',
                        'Encoding' => 'WinAnsiEncoding',
                        'BaseFont' => 'Helvetica');
    my $f2 = $pdf->font('Subtype'  => 'Type1',
                        'Encoding' => 'WinAnsiEncoding',
                        'BaseFont' => 'Helvetica-Bold');
    my $f3 = $pdf->font('Subtype'  => 'Type1',
                        'Encoding' => 'WinAnsiEncoding',
                        'BaseFont' => 'Times-Italic');
#----------------------------------------------------------------------------------------------------
my ($permission, $cookie, $template) = tmpl_read(
        {
            dbh             => $dbh,
            cgi             => $cgi,
            tmplFile        => 'marc21/print_pdf.tmpl',
        }
);
#----------------------------------------------------------------------------------------------------

if ($rid) {
    # See Search.pm for more info on use attribute.
    my $pqf = "\@attr 1=12 $rid";
    #my ($resultSize, $marcxml) = srch_searchRecord($dbh, $zid, 'f', $pqf, 1, 1);
    my ($resultSize, $marcxml) = srch_searchRecord($dbh, 0, 'f', $pqf, $ENV{'Z_INDEX_BASE'}, 1);
    my @rec = mc21_parseRecord($marcxml->[0]);
    $template->param(
        rec => \@rec,
    );

    printMarc_pdf(\@rec);
       #================= OPEN PDF File ========================
       #my $mypdf ="../circ/mypdf.pdf";
          open PDF, "<$mypdf";
            print $cgi->header(
                -type           => 'application/pdf',
                -attachement    => 'marcPrt.pdf'
            );
            while (<PDF>) {
                print $_;
            }
            close PDF;
       #=======================================================
       
}
else {
    $template->param(
        error => 1,
    );
    tmpl_write($dbh, $cgi, $cookie, $template);
}
#----------------------------------------------------------------------------------------------------
sub printMarc_pdf{
    my($rec)=@_; 
    my $page  ;
    my ($x,$y,$x1,$y1);
    my $rowNo =1;
    my $rowPerPage=26; 
    my $heightTbl;   
    my $rowspan;
    
    # Add a page which inherits its attributes from $root
    my $page =  $root->new_page;
    # Prepare a Table of Content
   $x =  X_LEFT_MARGIN ;                      #x_topleft
   $y =  Y_PAGE - ($rowNo  * ROW_HEIGHT);     #y_topleft
   $x1=  X_PAGE -  X_LEFT_MARGIN;             #x_topright
   $y1=  Y_PAGE - ($rowNo  * ROW_HEIGHT);     #y_topright

    $page->line($x,$y,$x1,$y1);
    $x = $x + X_LEFT_MARGIN ;
    for(my $i=0; $i<(scalar(@$rec)); $i++){
        if ($rowNo == $rowPerPage ){
            $rowNo =1;
            $page = $root->new_page;
           $x =  X_LEFT_MARGIN ;                      #x_topleft
           $y =  Y_PAGE - ($rowNo  * ROW_HEIGHT);     #y_topleft
           $x1=  X_PAGE -  X_LEFT_MARGIN;             #x_topright
           $y1=  Y_PAGE -  ROW_HEIGHT;     #y_topright
         }
       
         $page->line($x,$y,$x1,$y);

        $y = $y -   ROW_HEIGHT;
        if (@$rec[$i]->{'leader'} ne''){
             $page->stringl($f2, 14, $x , $y, 'leader');    
             $page->stringl($f2, 14, $x + (COL1_WIDTH + 3 * COL2_WIDTH), $y, @$rec[$i]->{'leader'});
        }
       else {
           if (@$rec[$i]->{'data'} ne''){
                $page->stringl($f2, 14, $x ,$y, @$rec[$i]->{'tag'});
                $page->stringl($f2, 14, $x + (COL1_WIDTH + 3* COL2_WIDTH), $y, @$rec[$i]->{'data'});
                 $y = $y -   ROW_HEIGHT;
                 $rowNo++;
             
           }
           else{
               
               if (@$rec[$i]->{'tag'}){
                  $rowspan = @$rec[$i]->{'rows'}; 
                  $page->stringl($f2, 14, $x ,$y, @$rec[$i]->{'tag'});
               }
              if (@$rec[$i]->{'ind1'}){
                  $page->stringl($f2, 14, $x+ (COL1_WIDTH + ($rowspan - 1)* COL2_WIDTH) ,$y, @$rec[$i]->{'ind1'});
              }
              if (@$rec[$i]->{'ind2'}){
                  $page->stringl($f2, 14, $x+ (COL1_WIDTH + ($rowspan - 1)* COL2_WIDTH) ,$y, @$rec[$i]->{'ind2'});
              }
              my $tmp=@$rec[$i]->{'subfield'};   
              foreach my $a(@$tmp){   
                 $page->stringl($f2, 14, $x+COL1_WIDTH ,$y,$a->{'code'});
                 $page->stringl($f2, 14, $x+ (COL1_WIDTH + ($rowspan - 1)* COL2_WIDTH) ,$y,  $a->{'data'});
                 $y = $y -   ROW_HEIGHT;
                 $rowNo++;
              }
              
           }  # if (@$rec[$i]->{'data'} ne''){

       }# if (@$rec[$i]->{'leader'} ne''){

    }
   
   
   #$page->stringc($f1, 12,X_PAGE + ROW_HEIGHT, Y_PAGE, "version $PDF::Create::VERSION");

    # Add something to the first page
    #$page->stringc($f1, 20, 306, 300,'by Fabien Tassin <fta@oleane.net>');

    # Add another page
    #my $page2 = $root->new_page;
    #$page2->line(0, 0, X_PAGE, Y_PAGE);
    #$page2->line(0,Y_PAGE , X_PAGE, 0);

   
    # Add the missing PDF objects and a the footer then close the file
    $pdf->close;

     }
#----------------------------------------------------------------------------------------------------

#tmpl_write($dbh, $cgi, $cookie, $template);
