#!/usr/bin/perl -w
use lib '/www/opals/module';
use Opals::Context("/etc/opals/conf/cay_we");
use strict;
use DBI;
use Getopt::Std;
use POSIX qw(
    ceil
    floor
);

use Opals::MarcXml qw(
    mxml_updateItemInfo
);

my $config = loadConfig("/etc/opals/conf/cay_we");
my $dbh = makeConnection($config);
END {
    if ($dbh) {
        $dbh->disconnect();
    }
}

$| = 1;
# fix -- update barcodes
my $sth = $dbh->prepare(<<_SQL_);
select distinct rid 
from opl_item
where barcode not regexp '^\_\_\_'  
order by rid 
_SQL_

#select distinct rid 
#from opl_ge852record r inner join opl_ge852request g on g.req_id=r.req_id && g.action='appendF' && r.req_id <25
#order by rid 

    $sth->execute;
    my $dir;
    while (my ($rid) = $sth->fetchrow_array) {
        if($rid){
            updateRecHoldings_xml($dbh,$rid);
        }
    }
    
    $sth->finish;


############################################################
sub updateRecHoldings_xml{
    my($dbh,$rid) =@_;
    my $zRoot   = $config->{'zRoot'};
    my $zPort   = $config->{'zPort'};
    my $zDatabase = $config->{'zDatabase'};
    my $dir     = "$zRoot/$zPort/record/$zDatabase/" . ceil($rid/1000);

    unless (-d $dir) {
            mkdir $dir, 0770;
    }        
     
    if (-f "$dir/$rid.xml") {
            my $xml = '';
            open  RECORD, "<$dir/$rid.xml";
            my $line;
            while (<RECORD>) {
                $line = $_;
                $xml .= $line;
            }
            my $orgXml=$xml;
            my $newSubFields="";
            my $found=0;
            while ($xml =~ s/([\s]*<datafield tag="852" ind1="[\d ]" ind2="[\d ]">([\s]*<subfield code="[\w\-]">.*<\/subfield>)+[\s]*<\/datafield>)//) {
                my $tmp852 =$1;
                my ($bc,$callNumber,$typeId,$location)=("","","G","");
                if ($tmp852 =~ m/<subfield code="p">(.*)<\/subfield>/) {
                    my $bc =$1;
                    if(!existInDb($dbh,$bc)){

                        if($tmp852 =~ m/<subfield code="-">(.*)<\/subfield>/){
                            $callNumber=$1;
                        }
                        if($tmp852 =~ m/<subfield code="c">(.*)<\/subfield>/){
                            $location=$1;
                        }
                        print "$tmp852 \n$rid --- $bc -- $callNumber -- $location\n";
                        addHolding($dbh,$rid,$bc,$typeId,$callNumber,$location);
                        mxml_updateItemInfo($dbh,$orgXml);
                     }
                }
            
            }
            close RECORD;
            

    }
}

############################################################
sub existInDb{
    my ($dbh,$bc)=@_;
    my $sth=$dbh->prepare("select  * from opl_item where barcode= ?");
    $sth->execute($bc);
    if(my $c = $sth->fetchrow_hashref){
        return 1;
    }
    return 0;
}
############################################################
sub addHolding{
    my  ($dbh,$rid,$barcode,$typeId,$callNumber,$location)=@_;

    my $sth=$dbh->prepare("insert into opl_item(rid,barcode,typeId,callNumber,location) values(?,?,?,?,?)");
    $sth->execute($rid,$barcode,$typeId,$callNumber,$location);
    $sth->finish;
}
############################################################
sub fixBc{
    my($bc)=@_;
    $bc =~ s/^\*+|\*+$//g;
    return $bc;
}


############################################################
sub makeConnection {
    my ($config) = @_;
    if (!$config) {
        return;
    }
    my ($db_driver, $db_name, $db_host, $db_port, $db_user, $db_password);

    $db_driver   = $config->{'db_driver'} || 'mysql';
    $db_name     = $config->{'db_name'};
    $db_host     = $config->{'db_host'};
    $db_port     = $config->{'db_port'}   || '3306';
    $db_user     = $config->{'db_user'};
    $db_password = $config->{'db_password'};

    my $dsn = "dbi:$db_driver:$db_name:$db_host:$db_port";

    return DBI->connect($dsn, $db_user, $db_password);
}


############################################################
sub loadConfig {
    my ($configFile) = @_;
#    print "Enter the config filename of Opals: ";
#    $configFile = <STDIN>;
    my $config = {};

    open CONF, $configFile || die "Cannot open file $configFile";
    while (<CONF>) {
        chomp;
        s/#.*//;                # remove comments
        next if /^\s*$/;        # ignore blank lines

        if (/^\s*(\w+)\s*=\s*(.*?)\s*$/) {
            $config->{$1} = $2;
        }
    }
    close CONF;
    
    return $config;
}
############################################################


exit 0;

