#!/usr/bin/perl

#use utf8;
use strict;
use CGI;

use Opals::Context;#use MARC::File::USMARC;
#use MARC::File::XML;

use HTML::Template;

use Opals::BookCover qw(
    bookCover_getUrl
    bookCover_amazon
    bookCover_google
    bookCover_syndetics
);
use Opals::SolrIndex qw(
    slr_getShelfList
);
use Opals::CallNumberUtil qw(    
    cn_getCallNumSortByLcc
);

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

my $cgi = CGI->new;
my $input = $cgi->Vars();


my $callNumber  = $input->{'callNumber'};
$callNumber="" if($callNumber =~ m/^video link$/gi);
my $location    = $input->{'location'};
my $offset      = $input->{'offset'};
my $size        = $input->{'size'};
my $dir         = $input->{'dir'};
my $curRid      = $input->{'curRid'};

my $isLccSystem=0;
if(Opals::Context->preference('classificationSystem') eq 'LCC'){
    $isLccSystem=1;
}


my $itemList=undef;my $itemList_r=undef;

if($callNumber && $callNumber ne ''){
    if($isLccSystem){
        $callNumber = cn_getCallNumSortByLcc($callNumber);
    }
    my $shelfParams={callNumber=>$callNumber,
                    location=>$location,
                    offset=>$offset,
                    size=>$size,
                    dir=>$dir,
                    curRid=>$curRid,
                    inclusive =>0,
                    isLccSystem=>$isLccSystem};

    if($dir eq 'left' || $dir eq 'right'){
        $itemList = slr_getShelfList($shelfParams);
    }
    else{
        $shelfParams->{'dir'}='left';
        $itemList =slr_getShelfList($shelfParams);
        $shelfParams->{'dir'}='right';
        $shelfParams->{'inclusive'}=1;
        my $itemList_r =slr_getShelfList($shelfParams);
        $itemList = [@$itemList,@$itemList_r ];

    } 

    getBookCover($itemList);
        

}

    my $rootDir   = Opals::Context->config('rootDir');
    my $template = HTML::Template->new(    
            filename            => "bookShelfitemList.tmpl",
            path                => "$rootDir/htdocs/theme/opals/ajax/search/",
            die_on_bad_params   => 0,
            cache               => 1,
            shared_cache        => 0,
            loop_context_vars   => 1,);

    $template->param(itemList=>$itemList) if(defined $itemList);
    print "Content-type: text/html\n\n";
    print $template->output;

#=======================================================
sub getBookCover{
    my($recList)=@_;
    my  $awsId =Opals::Context->preference('amazonId');
    my  $awsSecretKey =Opals::Context->preference('amazonSecreteKey');
    my  $syndeticsId =Opals::Context->preference('syndeticsId');
    if($syndeticsId ne''){
        bookCover_syndetics($recList);
    }
    elsif($awsId ne '' && $awsSecretKey ne ''){
        bookCover_amazon($recList,$awsId,$awsSecretKey);
    }
    else{
        bookCover_google($recList);
    }

}

#---------------------------------------------------------------------------------------




