#!/usr/bin/perl 
#
#
use lib("/www/opals/module");
#use Opals::Context('/etc/opals/conf/odev');
#use Opals::Context("/etc/opals/conf/_MY_SITE_");

use strict;
use Opals::Pathfinder qw(
    pf_parsePfXml
    pf_getRecById
);
use Opals::Constant; 
use Date::Calc::Object qw(
    :all
);
use Digest::SHA qw(
    sha1_hex
    sha512_hex
);

use POSIX qw(
    ceil
    floor
);

use CGI;
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;


$dbh->do(<<_SQL_);
CREATE TABLE IF NOT EXISTS pf_ridMap(
        `id` int(10) unsigned NOT NULL AUTO_INCREMENT,   
        `rid` int(10) unsigned NOT NULL DEFAULT '0',   
        `pfId` int(10) unsigned NOT NULL, 
        `modDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        `notes` varchar(255)  DEFAULT NULL, 
        PRIMARY KEY (`id`),KEY `id_2` (`id`,`pfId`))  
ENGINE=MyISAM DEFAULT CHARSET=latin1
_SQL_

$dbh->do("truncate table pf_ridMap ");

my  $sth_insert = $dbh->prepare(<<_STH_);
        insert into pf_ridMap  
        set rid=?,  pfId=?
_STH_


my $sth = $dbh->prepare(<<_STH_);
    select pfId from pf_record  order by pfId
_STH_
    $sth->execute();

while( my ($pfId) = $sth->fetchrow_array){
    if($pfId && $pfId>0){
        my $pf=pf_getRecById($dbh,$pfId);
        if($pf){
            my $pfRec=pf_parsePfXml($pf->{'xml'});
            my $rid=0;
            foreach my $bookRs(@{$pfRec->{'libraryRsList'}}){
                foreach my $b (@{$bookRs->{'bookList'}}){
                    if($b->{'rid'}>0 ){
                        $rid=$b->{'rid'};
                        if(validateRid($dbh,$rid)){
                            $sth_insert->execute($rid,$pfId);
                        }
                    }
                }
            }
        } #END:if($pf)
    }        
}

#=================================================================================================
sub validateRid{
    my($dbh,$rid)=@_;
    my ($r) =$dbh->selectrow_array("select rid from opl_item where rid=$rid && available=1");
    return $r?1: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;
}

