#!/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_getRecById
   );
use CGI;
use DBI;
my $dbh = Opals::Context->dbh();

my $pfId=18;
my $pfXmlFmtStr="<record><pfId>%s</pfId><title>%s</title><author>%s</author><intro>%s</intro><subject>%s</subject><libraryRs><header/><description/>%s</libraryRs><internetRs><header/><description/>%s</internetRs></record>";


my $bookFmtStr="<book><rid>%s</rid><title>%s</title><author>%s</author><pubName>%s</pubName><pubPlace>%s</pubPlace><pubDate>%s</pubDate><callNumber>%s</callNumber><isbnList>%s</isbnList></book>";

my $webFmtStr="<internet><title>%s</title><author>%s</author><url>%s</url><description>%s</description></internet>";

my $sth=$dbh->prepare("select pfId,title,author,introduction,subjectArea from pf_record where xml is null ");

my $sth_updateXml=$dbh->prepare("update pf_record set xml=? where pfId=?");
my $sth_insertSbj=$dbh->prepare("insert into pf_subject set subject=?, pfId=?");

$sth->execute();
while(my ($pfId,$title,$author,$introduction,$subjectArea)=$sth->fetchrow_array){
    foreach my $str ($title,$author,$introduction,$subjectArea){
        $str=escapeXml($str);
    }
    my $pfXml="";
    my $libRsXml=getLibRsXml($dbh,$pfId);
    my $webRsXml=getWebRsXml($dbh,$pfId);
    $pfXml = sprintf($pfXmlFmtStr,$pfId,$title,$author,$introduction,$subjectArea,$libRsXml,$webRsXml);
    $sth_updateXml->execute($pfXml,$pfId);
    $sth_insertSbj->execute($subjectArea,$pfId);
    #print "$pfXml\n";

   
}

sub getLibRsXml{
    my($dbh,$pfId)=@_;
    my $libRsXml="";
    my $sth=$dbh->prepare("select rid,title,author,pubName,pubPlace,pubDate,callNumber,isbn from pf_bookRs where pfId=?");
    $sth->execute($pfId);
    while(my ($rid,$title,$author,$pubName,$pubPlace,$pubDate,$callNumber,$isbn) =$sth->fetchrow_array){
        foreach my $str ($title,$author,$pubName,$pubPlace,$pubDate,$callNumber,$isbn){
            $str=escapeXml($str);
        }

        $libRsXml .= sprintf($bookFmtStr,$rid,$title,$author,$pubName,$pubPlace,$pubDate,$callNumber,$isbn);
    }
    return $libRsXml;
}
sub getWebRsXml{
    my($dbh,$pfId)=@_;
    my $webRsXml="";
    my $sth=$dbh->prepare("select title,author,url,description from pf_webRs where pfId=?");
    $sth->execute($pfId);
    while(my ($title,$author,$url,$description) =$sth->fetchrow_array){
        foreach my $str ($title,$author,$url,$description){
            $str=escapeXml($str);
        }
        $webRsXml .= sprintf($webFmtStr,$title,$author,$url,$description);
    }
    return $webRsXml;
}

sub escapeXml {
    my ($str)=@_;

    $str =~ s/&/&amp;/g;
    $str =~ s/>/&gt;/g;
    $str =~ s/</&lt;/g;
    $str =~ s/"/&quot;/g;
    $str =~ s/'/&apos;/g;

    return $str;

}
