#!/usr/bin/perl -w

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

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...

print $config->{'db_name'}, ': create table opl_subjects...';
$dbh->do(<<_SQL_)
create table if not exists opl_subjects (
    id          int(10) unsigned NOT NULL auto_increment,
    subject     text,
    recCount    int(10) unsigned NOT NULL default '0',
    PRIMARY KEY (id),
    FULLTEXT KEY subject (subject)
) engine=MyISAM
_SQL_
|| exit 1;
print " done.\n";

my $zdbDir = $config->{'zRoot'} .'/'
           . $config->{'zPort'} .'/'
           . 'record' .'/'
           . $config->{'zDatabase'};

my $indexDir;

my $sth = $dbh->prepare(<<_SQL_);
select  rid
from    opl_marcRecord
order by rid asc
_SQL_
$sth->execute;
my $dir;
while (my ($rid) = $sth->fetchrow_array) {
    addSubjects($dbh, $zdbDir, $rid);
}
$sth->finish;

# Codes end.

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


sub addSubjects {
    my ($dbh, $zdbDir, $rid) = @_;

    my $record = '';
    my $dir = ceil($rid/1000);
    if (! -f "$zdbDir/$dir/$rid.xml") {
        print "ERROR: $zdbDir/$dir/$rid.xml: not found.\n";
        return;
    }

    #print "$rid\n";
    #return;

    open MARCXML, "<$zdbDir/$dir/$rid.xml";
    while (<MARCXML>) {
        $record .= $_;
    }
    close MARCXML;

    addSubjects_to_database($dbh, $record, $rid);
}
############################################################


sub addSubjects_to_database{
    my ($dbh, $record, $rid) = @_;

    my @subject = listSubject($record);
    my $sql;
    my $sth;     
   foreach my $s (@subject) {
    $sth = $dbh->prepare(<<_SQL);
select id from opl_subjects 
where   subject = ?
_SQL

     $sth->execute($s);

    my ($rec) =$sth->fetchrow_hashref;
    if($rec){
$sql = <<_SQL_;
update opl_subjects 
set    recCount=recCount+1
where   id = ?
_SQL_
   my $rv = $dbh->do($sql, undef, $rec->{'id'});
        
    }
    else{
$sql = <<_SQL_;
insert into opl_subjects
set    subject=? ,
       recCount=recCount+1
_SQL_
   my $rv = $dbh->do($sql, undef, $s);
    }

    }
}
############################################################


sub listSubject {
    my ($xml) = @_;

    my @subject;
    my ($subj, $field, $code, $data);
    while ($xml =~ s/([\s]*<datafield tag="6[\d]{2}" ind1="[\d ]" ind2="[\d ]">([\s]*<subfield code="[\w\-]">.*<\/subfield>)+[\s]*<\/datafield>)//) {
        $field = $1;
        $subj = '';
        while ($field =~ s/<subfield code="([\w\-])">(.*)<\/subfield>//) {
            $code = $1;
            $data = $2;
            $data =~ s/[\.|,|:|;]*$//g;
            if ($code !~ m/^(2|-)$/) {
                $subj = ($subj ne '') ? "$subj -- $data" : $data;
            }
        }
        push @subject, $subj;
    }

    return @subject;
}
