#!/usr/bin/perl 
use lib("/www/opals/module");

=item
command to update all the sites:

for i in `ls /etc/opals/conf/`; do cp -p /www/opals/script/fillCallNumber /tmp/urt; perl -pi -e "s/_MY_SITE_/$i/" /tmp/urt; sudo /tmp/urt; done

=cut

#use Opals::Context('/etc/opals/conf/ztest');
use Opals::Context("/etc/opals/conf/_MY_SITE_");
#use Opals::Context("/etc/opals/conf/pag_pag");
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_parseDewey
    cn_getCallNumSortByDewey
    cn_getCallNumSortByLcc
);
use Opals::Search qw(
    srch_getRecType
    srch_recordBrief
);

use MARC::Record;
use MARC::Field;
use MARC::File::XML;

use CGI;
use DBI;

my $dbh = Opals::Context->dbh();
my $zRoot   = Opals::Context->config('zRoot');
my $zPort   = Opals::Context->config('zPort');
my $zDatabase = Opals::Context->config('zDatabase');

updateCallNumber();
#############################################################################################################

sub updateCallNumber{
    
#    my $sth =$dbh->prepare("select distinct rid from opl_item where callNumber is null  or callNumber =''");
 #   my $sth =$dbh->prepare("select distinct rid from opl_item where callNumSort_dewey is null or callNumSort_dewey =''");
    my $sth =$dbh->prepare("select distinct rid from opl_item order by rid");
    my $sth_updateCallNumber=$dbh->prepare("update opl_item set callNumber=? ,callNumSort_dewey=? , callNumSort_lcc=?  where barcode= ?");
    $sth->execute();
    while(my ($rid) = $sth->fetchrow_array()){
        my $xml =getMarcXml($rid);
        my $record= srch_recordBrief($xml);
        my $itemList = $record->{'itemList'};
        foreach my $itm (@$itemList) {
            my $deweySort=cn_getCallNumSortByDewey($itm->{'callnumber'});
            my $lccSort  =cn_getCallNumSortByLcc($itm->{'callnumber'});
            $sth_updateCallNumber->execute($itm->{'callnumber'},$deweySort,$lccSort , $itm->{'barcode'});
        }

    }
    $sth_updateCallNumber->finish;
    $sth->finish;
}

sub getMarcXml{
    my ($rid)= @_;
    my $xml="";
    my $dir = "$zRoot/$zPort/record/$zDatabase/" . ceil($rid/1000);
    open REC_DEL, "<$dir/$rid.xml";
    while (<REC_DEL>) {
        $xml .= $_;
    }
    close REC_DEL;

    return $xml;

}



