#!/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::Ebook qw(
    eb_saveLicense
    eb_getLicenseList
);
use  Opals::Epub;

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   => 'ebook_mgmt',
        }
);
use  Opals::Epub;
use Opals::WebServiceEbookClient qw( 
    wsc_uploadEbook
    wsc_addEbook
);

use XML::SAX;

my $uid       = $ENV{'curUserId'};
my $fid     = $input->{'epubFileId'};
my $bid       = $input->{'bid'};
my $metaData =undef;
if ($permission && $permission->{'ebook_mgmt'}) {
   my $licId       = $input->{'licId'};
   my $licenseType = ($input->{'licenseType'}) || 'paid';
   if($fid && $fid ne'' && -f "/tmp/$fid"){
        

        my $epubFile="/tmp/$fid" ;
        my $rs = wsc_uploadEbook({epubFile =>[$epubFile]});
        $bid=$rs->{'bid'};
        $metaData=$rs->{'metadata'};
    }
    elsif(defined $bid && $bid >0){
        my $rs = wsc_addEbook({bid=>$bid});
        $bid=$rs->{'bid'};
        $metaData=$rs->{'metadata'};

    }
    if($bid){
        my $licInfo={
                bid             => $bid,
                licenseType     => $licenseType,
                noLicense       => $input->{'noLicense'},
                datePurchase    => $input->{'purchaseDate'},
                poNum           => $input->{'poNum'},
                vendor          => $input->{'vendor'},
                startDate       => $input->{'startDate'},
                endDate         => $input->{'endDate'},
                note            => $input->{'note'}
        };
        $licId =eb_saveLicense($dbh,$uid,$licInfo);     


        my $licList  = eb_getLicenseList($dbh,$bid);
        $template->param(title      =>$metaData->{'title'},
                         author     =>$metaData->{'author'},
                         ISBN       =>$metaData->{'ISBN'},
                         description=>$metaData->{'description'},
                         bid        =>$bid,
                         licList    =>$licList
                         
                );
    }

}

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

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



