#!/usr/bin/perl -w
#
# This script is used to remove all duplicate barcodes.
#
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;
}
#
#sudo  /www/opals/script/addDecimal2price -c /etc/opals/conf/wswhe_fane
#
my $config = loadConfig($configFile);
my $dbh = makeConnection($config);
END {
    if ($dbh) {
        $dbh->disconnect();
    }
}

$| = 1;
# fix -- update barcodes
my $defaultPrice="0.00";
my $sql_bk="select   distinct rid from     opl_item where    price >100 && right(price,1)=0 && price <3000";
my $sql   ="select   rid,max(price) from     opl_item  group by rid ";
my $sth = $dbh->prepare($sql);

    $sth->execute;
    my $dir;
   my $count =0;
    while (my ($rid,$maxPrice) = $sth->fetchrow_array) {
        if($rid){
            #print "$rid\n";
            $maxPrice=fixPrice($maxPrice)if($maxPrice=~ m/^[0-9]+$/);
            addDecimal2Price($dbh,$rid,$maxPrice);
        }
    }
    print "$count\n"; 
    $sth->finish;
############################################################
sub fixPrice{
    my($price)=@_;
    my $strLen=length($price);
    if($strLen>4){
        my $i=4;
        for($i=4; $i<$strLen;$i++){
           last if(substr($price,$i,1) =="0");
        }
        $price=substr($price,0,$i);
    }
    $price=sprintf("%.2f",int($price)/100);
    return $price;
}

############################################################
sub addDecimal2Price{
    my($dbh,$rid,$defaultPrice) =@_;
    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;
                }
            }
            close RECORD;
            my $newSubFields="";
            my $found=0;
            my($bc,$oldPrice,$newPrice)=("","","");
            while ($xml =~ s/([\s]*<datafield tag="852" ind1="[\d ]" ind2="[\d ]">([\s]*<subfield code="[\w\-]">.*<\/subfield>)+[\s]*<\/datafield>)//) {
                my $tmp852 =$1;
                ($bc,$oldPrice,$newPrice)=("","",$defaultPrice);
                if($tmp852 =~ m/<subfield code="p">(.*)<\/subfield>/gi){
                    $bc=$1;
                    next if($bc eq'');
                }
                if($tmp852 =~ m/<subfield code="9">(.*)<\/subfield>/gi){
                    $oldPrice=$1;
                    $oldPrice =~ s/^\s+|\s+$//g;
                    $newPrice=$oldPrice;
                    if($newPrice eq '' || $newPrice eq '0'|| $newPrice eq '0.00'){
                        $newPrice=$defaultPrice;
                    }
                    elsif($newPrice =~ m/^[0-9]+$/){
                        $newPrice=fixPrice($newPrice);
                    }
                    if($oldPrice ne $newPrice){
                        $tmp852 =~ s/<subfield code="9">(.*)<\/subfield>/<subfield code="9">$newPrice<\/subfield>/gi;
                    }
                 }
                 else{
                     $tmp852 =~ s/(.*)(<\/datafield>)/$1  <subfield code="9">$newPrice<\/subfield>\n  $2/gi;
                 }
                 if($oldPrice ne $newPrice){
                        updatePrice($dbh,$bc,$newPrice);
                        print "$bc: [$oldPrice] [$newPrice]\n";  
                        $found=1;  
                 }
                
                 $newSubFields .= $tmp852;
            }
            return if(!$found);
            $xml =~ s/[\s]*<\/record>/$newSubFields\n<\/record>/;
            open  RECORD, ">$dir/$rid.xml";
            #open  RECORD, ">/tmp/aaa/$rid.xml";
            print RECORD $xml;
            close RECORD;

    }
}

############################################################
sub updatePrice{
    my($dbh,$bc,$price)=@_;
    $dbh->do("update opl_item set  price='$price' where barcode='$bc'");
    $dbh->do("update opl_itemInfo set sf852Data ='$price' where sf852Code='9' && barcode='$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;

