#!/usr/bin/perl -w

use strict;
use DBI;
use Getopt::Std;
use POSIX qw(
    ceil
    floor
);

my %options = ();
getopts("c:p:l:",\%options);
my $configFile = $options{c};
my $bcPrefix="";
my $bcLength=10;
if (!$configFile || ! -f $configFile) {
    print "Usage: $0 -c CONFIG_FILE\n -p BC_PREFIX -l BC_LENGTH";
    exit 1;
}
$bcPrefix=$options{p} if(exists($options{p}));
$bcLength=$options{l} if(exists($options{l}));
my $config = loadConfig($configFile);
my $dbh = makeConnection($config);
END {
    if ($dbh) {
        $dbh->disconnect();
    }
}

$| = 1;

   my $zRoot   =   $config->{'zRoot'};
   my $zPort   =   $config->{'zPort'};
   my $zDatabase = $config->{'zDatabase'};



    #my $sth = $dbh->prepare("select rid,barcode,newBarcode from tmp_bc order by rid ");
    my $sth = $dbh->prepare("select rid,barcode from opl_item order by rid ");
    #my $sth = $dbh->prepare("select distinct rid from opl_item order by rid ");
    #my $sth = $dbh->prepare("select distinct rid from opl_item  where barcode not regexp '^\_\_\_' order by rid ");
    $sth->execute;
    my $count=1;
    #while (my ($rid,$barcode,$newBarcode) = $sth->fetchrow_array) {
    while (my ($rid,$barcode) = $sth->fetchrow_array) {
        #updateRecordBc($dbh,$rid,$barcode,$newBarcode);
        #resetRecordBc($dbh,$rid);
        checkRecordBc($dbh,$rid,$barcode);
        #getRecordBc($dbh,$rid);
        print "." if($count%100 ==0);
        print "\n" if($count%1000 ==0);
        $count++;
    }
    #$dbh->do("drop table tmp_bc");

    print "\ndone.\n";

################################################################################
sub updateRecordBc{
    my ($dbh,$rid,$newBc,$oldBc)=@_;
    my $dir     = "/tmp/pnw_ypxa/" . ceil($rid/1000);
    
    if (-f "$dir/$rid.xml") {
        my $xml = '';
        open  RECORD, "<$dir/$rid.xml";
        my $line;
        while (<RECORD>) {
            $line = $_;
            if ($line !~ m/<subfield code="-"/) {
                $xml .= $line;
            }
        }
        my $newSubFields="";
        while ($xml =~ s/([\s]*<datafield tag="852" ind1="[\d ]" ind2="[\d ]">([\s]*<subfield code="[\w\-]">.*<\/subfield>)+[\s]*<\/datafield>)//) {
            my $tmp852 =$1;
            my $tmpBc=$oldBc;
            $tmpBc=~ s/([.+\$\\\/])/\\$1/g;
            if($tmp852 =~ s/<subfield code="p">($tmpBc)<\/subfield>/<subfield code="p">$newBc<\/subfield>/gi){
		print "$rid: $tmpBc : $oldBc";
            }
            $newSubFields .= $tmp852;
        }
        close RECORD;
            $xml =~ s/[\s]*<\/record>/$newSubFields\n<\/record>/;

            open  RECORD, ">$dir/$rid.xml";
            print RECORD $xml;
            close RECORD;

    }
    

}
################################################################################
sub checkRecordBc{
    my ($dbh,$rid,$bc)=@_;
    my $dir     = "/tmp/pnw_ypxa/" . ceil($rid/1000);
    
    if (-f "$dir/$rid.xml") {
        my $xml = '';
        open  RECORD, "<$dir/$rid.xml";
        my $line;
        while (<RECORD>) {
            $line = $_;
            if ($line !~ m/<subfield code="-"/) {
                $xml .= $line;
            }
        }
        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;
            if($tmp852 =~ m/<subfield code="p">$bc<\/subfield>/){
		$found=1;
		last;
            }
        }
	if(!$found){
		print "$rid :$bc\n";
	}
        close RECORD;

    }

}
################################################################################
sub getRecordBc{
    my ($dbh,$rid)=@_;
    my $dir     = "/tmp/pnw_ypxa/" . ceil($rid/1000);
    my $sth=$dbh->prepare("insert into tmp_bcCheck set barcode=?,rid=?");
    if (-f "$dir/$rid.xml") {
        my $xml = '';
        open  RECORD, "<$dir/$rid.xml";
        my $line;
        while (<RECORD>) {
            $line = $_;
            if ($line !~ m/<subfield code="-"/) {
                $xml .= $line;
            }
        }
        while ($xml =~ s/([\s]*<datafield tag="852" ind1="[\d ]" ind2="[\d ]">([\s]*<subfield code="[\w\-]">.*<\/subfield>)+[\s]*<\/datafield>)//) {
            my $tmp852 =$1;
            if($tmp852 =~ m/<subfield code="p">(.*)<\/subfield>/){
		my $bc=$1;
		$sth->execute($bc,$rid);
            }
        }
        close RECORD;

    }


}

################################################################################
sub resetRecordBc{
    my ($dbh,$rid)=@_;
    my $dir     = "/tmp/pnw_ypxa/" . ceil($rid/1000);
    my $sth=$dbh->prepare("select barcode from opl_item where rid=? && barcode not regexp '^\_\_\_' order by barcode");
    $sth->execute($rid);
    my @bcArr=();
    while(my ($bc)=$sth->fetchrow_array){
        push @bcArr,$bc;
    }
    my $i=0;
    if (-f "$dir/$rid.xml") {
        my $xml = '';
        open  RECORD, "<$dir/$rid.xml";
        my $line;
        while (<RECORD>) {
            $line = $_;
            if ($line !~ m/<subfield code="-"/) {
                $xml .= $line;
            }
        }

       my $newSubFields="";
       while ($xml =~ s/([\s]*<datafield tag="852" ind1="[\d ]" ind2="[\d ]">([\s]*<subfield code="[\w\-]">.*<\/subfield>)+[\s]*<\/datafield>)//) {
            my $tmp852 =$1;
            my $tmpBc=@bcArr[$i];
            if($tmp852 =~ s/<subfield code="p">(.*)<\/subfield>/<subfield code="p">$tmpBc<\/subfield>/gi){
		$i++;
            }
            $newSubFields .= $tmp852;
        }
        close RECORD;
        $xml =~ s/[\s]*<\/record>/$newSubFields\n<\/record>/;

        open  RECORD, ">$dir/$rid.xml";
        print RECORD $xml;
        close RECORD;

        
    }


}

exit 0;


################################################################################

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;
} 
############################################################
