#!/usr/bin/perl -w
#
# This script is used to remove all duplicate barcodes.
#
# This script is use to restore the "/" that are missing from the import process.
#
# NOTE: before running this script, use the checkMissingImport script
# 	to find the missing barcode, copy table tmp_importCheck table 
#       to tmp and add column barcode_match with data for barcode column
#       but without the "/" at the end.


use strict;
use DBI;
use Getopt::Std;
use POSIX qw(
    ceil
    floor
);
my %options = ();
getopts("c:",\%options);
my $configFile = $options{c};
if (!$configFile || ! -f $configFile) {
    print "Usage: $0 -c CONFIG_FILE\n";
    exit 1;
}

my $config = loadConfig($configFile);
my $dbh = makeConnection($config);
END {
    if ($dbh) {
        $dbh->disconnect();
    }
}

$| = 1;
# fix -- update barcodes
my $sth = $dbh->prepare(<<_SQL_);

select   distinct i.rid,t.barcode,t.barcode_match  
from     opl_item i inner join tmp t on t.barcode_match=i.barcode
where    t.barcode regexp '/' 
_SQL_

    $sth->execute;
    my $dir;
   my $count =0;
    while (my ($rid,$newBc,$oldBc) = $sth->fetchrow_array) {
        if($rid){
            print "$rid\n";
            fixRecBc($dbh,$rid,$newBc,$oldBc);
        }
    }
    print "$count\n"; 
    $sth->finish;


############################################################
sub fixRecBc{
    my($dbh,$rid,$newBc,$oldBc) =@_;
    my $zRoot   = $config->{'zRoot'};
    my $zPort   = $config->{'zPort'};
    my $zDatabase = $config->{'zDatabase'};
    my $dir     = "$zRoot/$zPort/record/$zDatabase/" . 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">$oldBc<\/subfield>/gi){
                        $count++;
                        $tmp852 =~ s/<subfield code="p">$oldBc<\/subfield>/<subfield code="p">$newBc<\/subfield>/gi;
                        updateBc($dbh,$oldBc,$newBc);
                        print "$rid : [$oldBc] [$newBc]\n";      
                    
                }
                $newSubFields .= $tmp852;
            }
            $xml =~ s/[\s]*<\/record>/$newSubFields\n<\/record>/;
            close RECORD;
            open  RECORD, ">$dir/$rid.xml";
            #open  RECORD, ">/tmp/aaa/$rid.xml";
            print RECORD $xml;
            close RECORD;

    }
}

############################################################
sub updateBc{
    my($dbh,$oldBc,$newBc)=@_;
    $dbh->do("update opl_item set barcode ='$newBc' where barcode='$oldBc'");
    $dbh->do("update opl_itemInfo set barcode ='$newBc' where barcode='$oldBc'");
    $dbh->do("update opl_itemstatus set barcode ='$newBc' where barcode='$oldBc'");
    $dbh->do("update opl_loan set barcode ='$newBc' where barcode='$oldBc'");
}

############################################################
sub isOnloan{
    my($dbh,$bc)=@_;
 my $sth = $dbh->prepare(<<_SQL_);
select barcode from opl_loan
where barcode=? && dateReturn is null
_SQL_

$sth->execute($bc);
if(my ($b) =$sth->fetchrow_array){
    return 0;
}
$sth->finish;

return 1

}


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

