#!/usr/bin/perl 

use strict;
use DBI;
use Getopt::Std;
use POSIX qw(
    ceil
);
use lib("/www/opals/module");
use Opals::Context('/etc/opals/conf/odev');
use strict;

use  Opals::Epub;
use  Opals::Ebook qw(
    eb_addEbook_test
);
use Opals::Indexer qw(
    ind_updateEbook
);
use Opals::Utility qw(
    util_escapeXml
);

use Opals::SolrIndex qw(
    slr_eb_search
    slr_eb_buildSearchQuery
);
my $dbh = Opals::Context->dbh();
my $cgi     = CGI->new;
my $input = $cgi->Vars();
END {
    if ($dbh) {
        $dbh->disconnect();
    }
}

use XML::SAX;
$| = 1;
# Codes start...
my $epubFile ="/tmp/insidethecell.epub";
my $ebook=Opals::Epub->new();

#print eb_addEbook_test($dbh,$epubFile),"\n";
 $ebook->parse($epubFile);
    my $metaData = {title        =>$ebook->getMetadataField("title"),
                    author       =>$ebook->getMetadataField("author"),
                    language     =>$ebook->getMetadataField("language"),
                    ISBN         =>$ebook->getMetadataField("ISBN"),
                    description  =>$ebook->getMetadataField("description"),
                    pubDate      =>$ebook->getMetadataField("pubDate"),
                    publisher    =>$ebook->getMetadataField("publisher"),
                    bookCover    =>$ebook->getBookCoverId()
                   };
        $ebook->reAssignUri("/ebook/102/");
        print $ebook->getFile("chapter1"),"\n";

#my  ($xmlDocs,$bidList)= getEbSolrDocList_update($dbh,1);
#print "$xmlDocs\n";


=item

  my $bid=4; 
  ind_updateEbook($dbh);
  ;

my @recType     = $cgi->param('recType');
    my $filter;
    $filter->{'recType'}=\@recType;
$input->{'sf0'} ="4";
$input->{'kw0'} ="painting";
my $lQuery=slr_eb_buildSearchQuery($input,$filter);

print  "$lQuery\n";

my $param={lQuery=>$lQuery,
           sortField=>4,sortDir=>0,
           offset=>0,size=>3};
 my $rs=undef;

 if($lQuery ne ''){
        $rs = slr_eb_search($param);  
    }
print  "$rs->{'hits'}\n";


=cut


sub getEbSolrDocList_update{
    my($dbh,$size)=@_;
    $size=1 if(!defined $size || $size<1);
    my @fields= qw(bid title author ISBN description publisher pubDate language);
    my $sth=$dbh->prepare("select * from eb_record where deleted=0 && bid=50");
    my $sth_toc=$dbh->prepare("select label from eb_toc where bid=?");
    $sth->execute();
    my $xmlDocs="";
    my $bidList=[];
    while( my $rec =$sth->fetchrow_hashref){
        push @$bidList,$rec->{'bid'};
        my $recData=[
                    {field=>"id",data=>"EB_" .$rec->{'bid'}},
                    {field=>"rid",data=>$rec->{'bid'}}];
        foreach my $f(@fields){
            push @$recData,{field=>$f,data=>util_escapeXml($rec->{$f})};
        }
        $sth_toc->execute($rec->{'bid'});
        while(my ($chapter) =$sth_toc->fetchrow_array){
             push  @$recData,{field=>"chapter",data=>util_escapeXml($chapter)};
        }
        $xmlDocs .= createEbSolrDoc($recData);

    }
    $sth->finish;
    $sth_toc->finish;
    return ($xmlDocs,$bidList);
}

############################################################
sub createEbSolrDoc{
    my($rec)=@_;
    my $xmlDoc="";
    my $indexFieldMap={
        id          =>"id",
        bid         =>"bid",
        rid         =>"rid",
        title       =>"title",
        author      =>"author",
        language    =>"language",
        ISBN        =>"isbn",
        description =>"summary",
        publisher   =>"namePublisher",
        pubDate     =>"datePublication",    
        chapter     =>"chapterTitle"
     };
     my $copyField={title=>["title_main","title_sort"],
                    author=>["author_main"]};
                
     foreach my $r(@$rec){
         $xmlDoc .= sprintf("<field name=\"%s\">%s</field>\n",$indexFieldMap->{$r->{'field'}},$r->{'data'});
         if(defined $copyField->{$r->{'field'}}){
             my $data =$r->{'data'};
            foreach my $cf(@{$copyField->{$r->{'field'}}}){
                if($cf eq "title_sort" ){
                    $data  =~ s/^the|^a//gi;
                    $data  =~ s/^\s//gi;
                }

                $xmlDoc .= sprintf("<field name=\"%s\">%s</field>\n",$cf,$data);
            }
         }
     }
    
   
    return "<doc><field name=\"db\">ebook</field>\n$xmlDoc</doc>";
}


