#!/usr/bin/perl

#use utf8;
use strict;
use CGI;
use Encode;

use PDF::API2;
use POSIX qw(
    ceil
    floor
);
use Date::Calc qw(Day_of_Week Week_Number Day_of_Year);
use Time::localtime;

use Opals::Context;
use Opals::User qw(
    user_getInformation
);
use Opals::Date qw(
    date_parse
    date_today
    date_text
    date_f005
);
use Opals::Template qw(
    tmpl_read
    tmpl_write
    tmpl_rangedPageList
);



my $rootDir = Opals::Context->config('rootDir');
my @allFontDirs = PDF::API2::addFontDirs "$rootDir/font/barcode/";
use constant    X_BOT_LEFT  =>  18;
use constant    Y_BOT_LEFT  =>  36;
use constant    X_TOP_RIGHT =>  594;
use constant    Y_TOP_RIGHT =>  756;

use constant    ROW_HEIGHT  =>  72;
use constant    COL_WIDTH  =>   198;
use constant    COL1_WIDTH  =>  184;
use constant    COL2_WIDTH  =>  198;
use constant    COL3_WIDTH  =>  193;


my $dbh = Opals::Context->dbh();
umask 007;
if ( ! -d '/tmp/pdf-tmp') {
    `mkdir -p '/tmp/pdf-tmp'`;
}
my $mypdf=`/bin/mktemp -p '/tmp/pdf-tmp'`;#'/tmp/tttbbbsss';#
END { $dbh->disconnect(); }

my $cgi = CGI->new;
my $input = $cgi->Vars();
my $ridList= $input->{'ridList'};
my $startLine=int($input->{'startPos'});
if($startLine>0){
    $startLine -=1;
}

#----------------------------------------------------------------------------------------------------

my $pdf  = PDF::API2->new(-file => $mypdf);
$pdf->mediabox(612,792);
my $normalFont = $pdf->corefont('Helvetica');  
my $boldFont = $pdf->corefont('Times New Roman-bold');  
my $barcodeFont = $pdf->ttfont('FREE3OF9.TTF');  
#my $barcodeFont = $pdf->ttfont('FRE3OF9X.TTF');  
#my $barcodeFont = $pdf->ttfont('BARCOD39.TTF');  
#my $barcodeFont = $pdf->ttfont('C39HDW2.TTF');  
#my $barcodeFont = $pdf->ttfont('C39HDW3.TTF');  
#my $barcodeFont = $pdf->ttfont('C39W2.TTF');  
#my $barcodeFont = $pdf->ttfont('C39W3.TTF');  

#----------------------------------------------------------------------------------------------------
my ($permission, $cookie, $template) = tmpl_read(
        {
            dbh             => $dbh,
            cgi             => $cgi,
            tmplFile        =>'report/itemacqst_prt.tmpl',
            reqPermission   => 'rpt_notice|rpt_catRec',
        }
);

    
    my $pagesize = 20;
    my $pNum = $input->{'pNum'};
    $pNum = 1 if ( !$pNum );

    my $dateFrom= $input->{'acqstFrom'};
    my $dateTo  = $input->{'acqstTo'};
    my $sort    = $input->{'sort'};
    $sort = 'dateImport' if ( !$sort );

    my $dateToday = date_f005();
    $dateToday =~ s/([\d]{4})([\d]{2})([\d]{2})[\d]+\.(0|1)/$1-$2-$3/;
    
    $dateFrom = $dateToday if ( !$dateFrom );
    $dateFrom .= " 00:00:00";
    $dateTo = $dateToday if ( !$dateTo );
    $dateTo .= " 23:59:59";

    $template->param(acqstFrom => $dateFrom);
    $template->param(acqstTo => $dateTo);
    $template->param(acqList => 1);

    my $recordList =   GetRecordAcquisitionList_all($dbh,$ridList, $dateFrom, $dateTo,$sort );
    printLabel($recordList);
 #================= OPEN PDF File ========================
#my $mypdf ="../circ/mypdf.pdf";
  open PDF, "<$mypdf";
    print $cgi->header(
        -type           => 'application/pdf',
        -attachement    => 'spineLabel.pdf'
    );
    while (<PDF>) {
        print $_;
    }
    close PDF;
    open ccc, '>/tmp/mypdf.lst';
    unlink $mypdf || warn "$mypdf: having trouble deleting $mypdf: $!\n";
    close ccc;


   
 ################################################################################
sub GetRecordAcquisitionList_all {
    my ($dbh, $ridList,$dateFrom, $dateTo, $sort) = @_;

       my $sql = <<_STH_;
select  m.title,m.author,i.callNumber,i.barcode 
from   opl_marcRecord as m inner join opl_item as i on i.rid=m.rid 
where   substring(i.barcode, 1, 3) <> '___' &&
        i.dateImport >= '$dateFrom' &&
        i.dateImport <= '$dateTo'
_STH_
    $ridList =~ s/,+/,/g;
    $ridList =~ s/(^,|,$)//g;
    $ridList =~ s/,$//;
    if ($ridList){
        $sql .= " && i.rid in ($ridList) ";
    }
$sort=$sort eq 'rid'?'i.rid':$sort;
        
$sql .= "  order by $sort asc  ";

    my $sth = $dbh->prepare($sql);
    $sth->execute();
    #my $odd = 0;
    my $pNum = -1;
    my @recordList;
    my $holdingList;
    while (my $rec = $sth->fetchrow_hashref) {
        $rec->{'barcode'} = uc($rec->{'barcode'});
        push @recordList, $rec;
    }
    $sth->finish;

    return \@recordList;
}

   
#----------------------------------------------------------------------------------------------------
sub printLabel{
    my($userData)=@_; 
    my  $page  ;
    my $pIndex=0;
    my($x1,$y1);
      ($x1,$y1)=(X_BOT_LEFT,Y_TOP_RIGHT- ROW_HEIGHT);

    if($startLine>0){
       $y1   = Y_TOP_RIGHT - $startLine* ROW_HEIGHT;
       $page = $pdf->page;
       $page = $pdf->openpage($pIndex++);
    }

    for(my $i=0; $i<(scalar(@$userData)); $i++){
       if(($i+$startLine)%10==0){ 
          $pIndex++;
          $y1  = Y_TOP_RIGHT ;
          $page = $pdf->page;
          $page = $pdf->openpage($pIndex);
       }
       $y1  -= ROW_HEIGHT;
       my @values;
       for (my $c=0 ; $c <3 ; $c++){
           if ($c==0){
               $x1  = X_BOT_LEFT;
               writeLabel_spine($page,$x1,$y1,@$userData[$i]->{'callNumber'});
           }
           else{
              $x1 = $x1+(COL_WIDTH); 
              writeLabel_card($page,$x1,$y1,@$userData[$i]->{'callNumber'},
                                            decode('utf8', @$userData[$i]->{'author'}),
                                            decode('utf8', @$userData[$i]->{'title'}),
                                            @$userData[$i]->{'barcode'});
            }
               
       }
         
     }       
     $pdf->save;
     $pdf->end();
}
   
#----------------------------------------------------------------------------------------------------
sub writeLabel_spine{
   my($page,$x,$y,$callNum)=@_;
    my $i=0;
    $x = $x + COL_WIDTH/2 - 30    ;
    $y = $y +ROW_HEIGHT/2+10;
    my $txt = $page->text;
    $txt->lead(9);
    $txt->textstart;
    # write Call number
    $txt->font($boldFont, 12);
    $txt->translate($x,$y);
    my @cArr=split(' ',$callNum);
    for(my $j=0; $j<scalar(@cArr);$j++){
        $txt->translate($x ,$y - $j*12);
        $txt->text(@cArr[$j]);
    }
=item
    my $overflowTxt = $txt->paragraph($callNum,10,9);
    while($overflowTxt ne ''){
        $i +=12;
        $txt->translate($x ,$y - $i);
        $overflowTxt = $txt->paragraph($overflowTxt,10,9);
    }
=cut    
   $txt->textend;
}  

sub formatTxt{
    my($f,$str,$fs,$w)=@_;
    my $txtWidth=$f->width($str);
    while($txtWidth*$fs > $w){
        $str=substr($str,0,length($str)-1);
        $txtWidth=$f->width($str);
        
    }
    return $str;
    
}
#----------------------------------------------------------------------------------------------------
sub writeLabel_card{
    my($page,$x,$y,$callNum,$author,$title,$bc)=@_;
    my $i=0;
    $y = $y +ROW_HEIGHT -15 ;
    my $txt = $page->text;
    $txt->lead(9);
    $txt->textstart;
    # write Call number
    $txt->font($normalFont, 9);
    $txt->translate($x ,$y);
    my @cArr=split(' ',$callNum);
    for(my $j=0; $j<scalar(@cArr);$j++){
        $txt->translate($x ,$y - $j*12);
        $txt->text(formatTxt($normalFont,@cArr[$j],9,30));
    }
    $x += 38;
    
    # write author 
    $txt->translate($x,$y);
    my $overflowTxt = $txt->paragraph($author,100,9);
    # write title 
    $txt->translate($x,$y-11);
    $overflowTxt = $txt->paragraph(" $title",100,9);
    if($overflowTxt ne ''){
        $txt->translate($x,$y-20);
        $overflowTxt = $txt->paragraph($overflowTxt,100,9);
    }
    # write BC 
    $txt->font($barcodeFont, 20);
    $txt->translate($x,$y-44);
    $overflowTxt = $txt->paragraph("*$bc*",160,28);
    $txt->font($normalFont, 8);
    $txt->translate($x,$y-53);
    $overflowTxt = $txt->paragraph($bc,120,9);
              
     $txt->textend;
}
    
   
