#!/usr/bin/perl

#use utf8;
use strict;
use CGI;
use Opals::Template qw(
    tmpl_read
    tmpl_write
    tmpl_preference
);
use Opals::Context;
use Opals::Constant;
use Opals::Locale qw(
    loc_getMsgFile
    loc_write
);
use Opals::Utility qw(
    util_resizeImg
);
use Time::HiRes qw(time);

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

my $cgi = CGI->new;
my $input = $cgi->Vars();
my ($permission, $cookie, $template) = tmpl_read(
        {
            dbh             => $dbh,
            cgi             => $cgi,
            tmplFile        => 'ebook/uploadEbook.tmpl',
            reqPermission   => 'pref_edit',
        }
);
use  Opals::Epub;
use XML::SAX;



my $fname     = $input->{'epubFile'};
if ($permission && $permission->{'pref_edit'}) {
   my $bid         = $input->{'bid'};
   my $licenseType = ($input->{'licenseType'}) || 'free';
   if($fname && $fname ne''){
        umask 002;         
        my $tmpUploadFile=`/bin/mktemp`;
        $tmpUploadFile =~ s/\n$//gi;
        system("chown apache.apache $tmpUploadFile");
        my $upload_filehandle = $cgi->upload("epubFile"); 
        open    UPLOADFILE, ">$tmpUploadFile" ;
        binmode UPLOADFILE;
        while ( <$upload_filehandle> ){
            print UPLOADFILE;
        }
        close UPLOADFILE;
        my $epub=Opals::Epub->new();
        $epub->parse("$tmpUploadFile");
        $bid = addBookf2Db($dbh,$epub,$licenseType);
    }
    if($bid){
        my $sth=$dbh->prepare("select title,author,ISBN,description,bookCover,bid,licenseType from eb_record where bid=?");
        $sth->execute($bid);
        if (my ($title,$author,$ISBN,$description,$bookCover,$bid,$licenseType) =$sth->fetchrow_array){
            $template->param(title      =>$title,
                             author     =>$author,
                             ISBN       =>$ISBN,
                             description=>$description,
                             bookCover  =>$bookCover,
                             bid        =>$bid,
                             licenseType=>$licenseType,
                             showPurchaseMgnt=>($licenseType eq 'purchase')
                    );
        }
        $sth->finish;

    }

}

#-------------------------------------------------------------
#Thu, Jan 07, 2010 @ 13:50:35 EST
my $msgValMap ={};
my $fileMsgMap            =loc_getMsgFile('user/userInfo.msg',$msgValMap);

loc_write($template,$fileMsgMap);
        
tmpl_write($dbh, $cgi, $cookie, $template);
############################################################
sub addBookf2Db{
    my ($dbh,$book,$licenseType)=@_;
    my $sth=$dbh->prepare("insert into eb_record set title=?,author=?,language=?,ISBN=?,description=?,pubDate=?,publisher=?,bookCover=?,licenseType=?");
    $sth->execute($book->getMetadataField("title"),
                  $book->getMetadataField("author"),
                  $book->getMetadataField("language"),
                  $book->getMetadataField("ISBN"),
                  $book->getMetadataField("description"),
                  $book->getMetadataField("pubDate"),
                  $book->getMetadataField("publisher"),
                  $book->getMetadataField("bookCover"),
                  $licenseType
                  );

    my $bid= $dbh->{'mysql_insertid'};
    addBookThumbnail($dbh,$bid,$book);
    $book->reAssignUri("/ebook/$bid/");
    addBookfTOC($dbh,$bid,$book);
    addBookSpine($dbh,$bid,$book);
    addBookFiles($dbh,$bid,$book);
    return $bid;

}
############################################################
sub addBookfTOC{
    my ($dbh,$bid,$book)=@_;
    my $sth=$dbh->prepare("insert into eb_toc set bid=?,playOrder=?,level=?,label=?,uri=?");
    foreach my $nav(@{$book->getTOC()}){
        $sth->execute($bid,$nav->{'playOrder'},$nav->{'level'},$nav->{'label'},$nav->{'src'});
    }

}
############################################################
sub addBookSpine{
    my ($dbh,$bid,$book)=@_;
    my $sth=$dbh->prepare("insert into eb_spine set bid=?,fid=?,playOrder=?");
    my $playOrder=1;
    foreach my $fid(@{$book->getSpine()}){
        $sth->execute($bid,$fid,$playOrder++);
    }
   
}

############################################################
sub addBookFiles{
    my ($dbh,$bid,$book)=@_;
    my $sth=$dbh->prepare("insert into eb_file set bid=?,fid=?,mimeType=?,content=compress(?)");
    my $manifest=$book->getManifest();
    foreach my $fid(keys %$manifest){
        my $fileCont=$book->getFile($fid);
        $sth->execute($bid,$fid,$manifest->{$fid}->{'media-type'},$fileCont);
    }
}
############################################################
sub addBookThumbnail{
    my ($dbh,$bid,$book)=@_;
    my $manifest=$book->getManifest();
    my $bookCoverId=$book->getMetadataField("bookCover");
    return if($bookCoverId eq "");

    my $bookCoverImg=$book->getBookCoverImg();
     if(defined $bookCoverImg){
        my $thumbnail = util_resizeImg($bookCoverImg,75,100);
        my $sth=$dbh->prepare("insert into eb_file set bid=?,fid='_opl_thumbnail',mimeType=?,content=compress(?)");
        $sth->execute($bid,$manifest->{$bookCoverId}->{'media-type'},$thumbnail);
    }

}


