#!/usr/bin/perl

# This script is not finished.

#use utf8;
use strict;
use CGI;
use Encode;
use POSIX qw(
    ceil
    floor
);

use Opals::Context;
use Opals::Template qw(
    tmpl_read
    tmpl_write
    tmpl_preference
);
use Date::Calc::Object qw(
    :all
);
use Opals::Search qw(
    srch_searchRecord
);

use Opals::Session qw(
    SessionHdl_get
);
use Opals::Locale qw(
    loc_getMsgFile
    loc_write
);

use Opals::MarcXmlParser; 
use Opals::RecordInfoHTML qw(
    rinfo_getPageNavForm_search
);
use Time::localtime;

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

my $cgi = CGI->new;
my $input = $cgi->Vars();
my $op = $input->{'op'};
my $sessionID = $cgi->cookie('globalSessionID');
my ($permission, $cookie, $template) = tmpl_read(
        {
            dbh             => $dbh,
            cgi             => $cgi,
            tmplFile        => 'util/bibsrc/bibliography.tmpl',
            reqPermission   => (($op eq 'email')? 'email':'none'),
        }
);
my $tm = localtime;
my $todayStr = sprintf("%04d-%02d-%02d", $tm->year+1900, ($tm->mon)+1, $tm->mday);

my $pageNavForm =rinfo_getPageNavForm_search($cgi);
    $template->param(pageNavForm=>$pageNavForm);
my $zid = $input->{'zid'};
($zid && $zid >= 0) || ($zid = 0);
my $odd_row=1;
#-----------------------------
   ## getBookCover(\@bibliography);
#-----------------------------
my $pref = tmpl_preference($dbh);
my $callNumSortFiled =($pref->{'classificationSystem'} eq 'LCC')?"callNumSort_LCC":"callNumSort_dewey";
my $bibformat     = $cgi->cookie('bibformat');
($bibformat && $bibformat =~ m/^(apa|mla|shelf)$/i) || ($bibformat = $pref->{'bibformat'});
($bibformat && $bibformat =~ m/^(apa|mla|shelf)$/i) || ($bibformat = 'mla');

#Thu, Jan 29, 2009 @ 12:08:05 EST
    my $sortOrder0 = $input->{'sortOrder0'};
    my $sortOrder1 = $input->{'sortOrder1'};
    my $sortOrder2 = $input->{'sortOrder2'};
    my $sortOrder3 = $input->{'sortOrder3'};
    my @sortOrder=();
    if($sortOrder0 && $sortOrder0 ne ''){
         @sortOrder=($sortOrder0,$sortOrder1,$sortOrder2,$sortOrder3);
    }
    elsif($bibformat eq 'shelf'){
        @sortOrder=('callnumber','author','titleSort','pubDateSort');        
    }
    else{
        @sortOrder=('author','titleSort','pubDateSort','callnumber');
    }
    foreach my $sf(@sortOrder){
        if($sf eq 'callnumber'){
            $sf= $callNumSortFiled;
        }
        if($sf eq 'pubDateSort'){
            $sf .=" DESC";
            next;
        }
    }

    my @bibliography=getBibList($dbh,$sessionID,\@sortOrder);
##Wed, Feb 16, 2011 @ 11:58:54 EST
#    foreach my $sf (@sortOrder){
#        if($sf eq 'pubDateSort'){
#            @bibliography = sort {lc($b->{$sf}) cmp lc($a->{$sf})} @bibliography; 
#
#        }
#        else{
#            @bibliography = sort {lc($a->{$sf}) cmp lc($b->{$sf})} @bibliography; 
#        }
#    }
 #

if($op eq 'ppreview' || $op eq 'email'){
    my $sumformat = $input->{'sumformat'};
    $template->param( sumformat   => $sumformat,);
    my $contformat = $input->{'contformat'};
    $template->param( contformat   => $contformat,);
}
else{
    $template->param( sumformat   => 1,);
    $template->param( contformat   => 1,);
}




foreach my $bibInfo (@bibliography){
    $bibInfo->{'odd'}=$odd_row;
    $odd_row =$odd_row?0:1;
}
$template->param(
    todayStr => $todayStr,
    bibliography    => \@bibliography,
    nBib            => scalar(@bibliography),
    bibformatList   => [
        {
            val => 'mla',
            opt => 'MLA',
            sel => ($bibformat =~ m/^mla$/i) ? 1:0,
        },
        {
            val => 'apa',
            opt => 'APA',
            sel => ($bibformat =~ m/^apa$/i) ? 1:0,
        },
        {
            val => 'shelf',
            opt => 'Shelf',
            sel => ($bibformat =~ m/^shelf$/i) ? 1:0,
        },
    ],
    op_ppreview     => (($op eq 'ppreview') ? 1:0),
    op_email        => (($op eq 'email') ? 1:0),
    $bibformat      => 1,
    viewBib         => 1,

);
$template->param(rs_json  => to_json(\@bibliography,{pretty=>1}));

my $stdMsgMap            =loc_getMsgFile('util/bibsrc/bibliography.msg');
loc_write($template,$stdMsgMap);

#-----------------------------------------------------------------------------
sub getBibList{
    my ($dbh,$sessionID,$sortFields)=@_;

    my @ridList=();
    my $sql="select distinct m.rid,s.note as userNote  from opl_sessionVar s
                            inner join opl_marcRecord m using(rid)
                            inner join opl_item i using(rid)                               
                         where var ='bibliography' && ssid= ? && i.barcode not regexp '^\_\_\_' order by ";
    $sql .= join(",",@$sortFields); 

    my $sth=$dbh->prepare($sql);
    $sth->execute($sessionID);

    my $marcXmlParser=undef;
    my $indexConfFile  = Opals::Context->config('sIndexConfig');
    $marcXmlParser=Opals::MarcXmlParser->new($indexConfFile) if (!defined $marcXmlParser);
    my @field2trim= qw( author title subtitle placePublication namePublisher datePublication);
    while (my $bib=$sth->fetchrow_hashref){
        my $rid  = $bib->{'rid'};
        my $userNote = $bib->{'userNote'} ;
        my $fname=recordPath($rid)."/$rid.xml";
        $bib=$marcXmlParser->getRecInfoGeneral_file($fname);
        $bib->{'userNote'}      = encode('utf8',$userNote);
        #$bib->{'callnum1St'}    = $bib->{'itemList'}[0]->{'callnumber'};
        $bib->{'callnumber'}    = $bib->{'itemList'}[0]->{'callnumber'};
        $bib->{'rid'}           = $rid; 
        foreach my $f(@field2trim){
            $bib->{$f}=trimPunctuation($bib->{$f});
        }
        $bib->{'format'}=@{$bib->{'format'}}[0]->{'item'};
        push @ridList, $bib;
    }
    $sth->finish;
    return @ridList;
   
}
#Mon, Jan 31, 2011 @ 14:42:04 EST
sub trimPunctuation{
    my($str)=@_;
    $str =~ s/[,;:.]+$//g;
    return $str;
}

#-----------------------------------------------------------------------------
sub recordPath {
    my ($rid) = @_;
    
    my $zRoot   = Opals::Context->config('zRoot');
    my $zPort   = Opals::Context->config('zPort');
    my $zDatabase = Opals::Context->config('zDatabase');
    my $dir     = "$zRoot/$zPort/record/$zDatabase/" . ceil($rid/1000);

    return $dir;
}


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