#!/usr/bin/perl 
use lib("/www/opals/module");
use Opals::Context('/etc/opals/conf/odev');
use strict;
use Opals::Constant; 
use Date::Calc::Object qw(
    :all
);
use Digest::SHA qw(
    sha1_hex
    sha512_hex
);

use POSIX qw(
    ceil
    floor
);
use Opals::CallNumberUtil qw(
       cn_parseLCC
       cn_getLccGrp
       cn_getCallNumSortByDewey
       cn_getCallNumSortByLcc
);

use Opals::POS;

use Opals::Search qw(
       srch_parseSearchTerm
);
use Time::localtime;


use Unicode::Normalize;

use Business::ISBN;
use MARC::Record;
use MARC::Field;
use MARC::File::XML;
use Encode;
use LWP::UserAgent;
use HTTP::Request::Common;
use URI::Escape;

use CGI;
use DBI;

my $dbh = Opals::Context->dbh();
END {
    if ($dbh) {
        $dbh->disconnect();
    }
}
my $ua = LWP::UserAgent->new;
   $ua->agent('Mozilla/8.0');

my $mimeType={"image/bmp"=>"bmp",
              "image/gif"=>"gif",
              "image/jpeg"=>"jpg",
              "image/png"=>"png"
             };



my $url='http://books.google.com/books?printsec=frontcover&frontcover&img=1&zoom=1&vid=ISBN';
   #$url='http://books.google.com/books?printsec=frontcover&frontcover&img=1&zoom=1&vid=ISBN9780060010294';
    
my $sth=$dbh->prepare("select id,isbn from thumbnail where path is null limit 5000 ");  
my $sth_update=$dbh->prepare("update thumbnail set path=? where id=?");
my $sth_total =$dbh->prepare("select count(*) from thumbnail where  path is null");
$sth_total->execute();
my ($total)=$sth_total->fetchrow_array;
my $count=0;

while($total>0){
    $sth->execute();
    while(my ($id,$isbn)= $sth->fetchrow_array){  
        print "$isbn\n";
        $total--;
        my $dir=getThumbnailPath($id);
        unless (-d $dir) {
            mkdir $dir, 0775;
        }
         
        my $req = GET $url .$isbn;
        my $res = $ua->request($req);
        if ($res->is_success) {
            my $type = $res->content_type();
            if(defined $mimeType->{$type}){
                my $path= "$dir/$isbn." . $mimeType->{$type} ;
            print $path ."\n";
                open  IMG,">$path" ;
                print IMG $res->content;
                close IMG;
                $sth_update->execute($path,$id);
            }

        }
        if($count++ ==25){
            my $t=getPauseTime();
            print "sleep $t seconds\n";
            sleep($t);
            $count=1;
        }

    }
}

#============================================================================
sub getThumbnailPath(){
    my($id)=@_;
   
   return "/data/thumbnail/" . ceil($id/1000);

}
#============================================================================
sub getPauseTime{
    my $timeTbl={weekday =>{daytime=> 90,evening=>300,night=>600}, # ~ (12*3600/45  + 4*3600/150 + 4*3600/300)*20 =  22080 /day
                saturday =>{daytime=>180,evening=>300,night=>600}, # ~ (12*3600/90  + 4*3600/150 + 4*3600/300)*20 =  12480 /day
                sunday   =>{daytime=>300,evening=>300,night=>600}  # ~ (12*3600/150 + 4*3600/150 + 4*3600/300)*20 =   8640 /day
           };                                                      # ~  5*22080 + 12480 +640                      = 131520 /week
    my $tod;
    my $dow;       
    my $t= localtime(time);
    my $hr=@$t[2];
    my $wd=@$t[6];

    if($hr>=8 && $hr <20){
        $tod='daytime';
    }
    elsif($hr>=20 && $hr <23){
        $tod='evening';
    }
    else{
        $tod='night';
    }
    
    if($wd==0){
        $dow='sunday';
    }
    elsif($wd==6){
        $dow='saturday';
    }
    else{
        $dow='weekday';
    }

    return floor($timeTbl->{$dow}->{$tod} * rand());
    

}

$| = 1;


