#!/usr/bin/perl -w

use strict;
use DBI;
use Getopt::Std;

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;
# Codes start...




# Codes end.

exit 0;
################################################################################
sub tb_record_findByRId_brief{

    my ($dbh, $rid) = @_;
    return if $rid eq '';

    my $sql = "select fId, fVal from tb_records where rid = ?";
    my $sth = $dbh->prepare($sql);
    $sth->execute($rid);
    my $recordInfo = ();
    while (my $rec = $sth->fetchrow_hashref) {
        if (! $recordInfo->{$rec->{'fId'}}){
            $recordInfo->{$rec->{'fId'}} => $rec->{'fVal'};
        }
    }
    $sth->finish;

    return $recordInfo;
}



sub eq_maxBarcodeDeleted {
    my ($dbh,$barcode) = @_;
     my $sql_bc = $barcode;
    $sql_bc =~ s/([*+?])/\\\\$1/g;
    $sql_bc .= '_';

    my ($maxBarcode) = $dbh->selectrow_array(<<_STH_);
select  max(barcode)
from    eq_items
where   barcode regexp '^___$sql_bc'
_STH_

    if ($maxBarcode && $maxBarcode =~ s/([\d]{3})$//) {
        my $dupCount = $1;
        $dupCount =~ s/^0{1,2}//;
        $dupCount++;
        $dupCount = sprintf("%0.3d", $dupCount);

        $maxBarcode .= $dupCount;
    }
    else {
        $maxBarcode = '___'.$barcode.'_000';
    }
    return $maxBarcode;
}


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