#!/usr/bin/perl
use strict;
use CGI;

use Opals::Context;
use Opals::Template qw(
    tmpl_read
    tmpl_write
);
use Opals::Pathfinder qw(
    pf_getRecById
);
use Opals::Locale qw(
    loc_getMsgFile
    loc_write
);

my $dbh = Opals::Context->dbh();
END { $dbh->disconnect(); }
my $pfXml="<record></record>";

my $cgi = CGI->new;
my $input = $cgi->Vars();
my ($permission, $cookieList, $template) = tmpl_read(
    {
        dbh             => $dbh,
        cgi             => $cgi,
        tmplFile        => 'pf/pfEditor.tmpl',
        reqPermission   => 'pf',
    }
);

if ($permission && $permission->{'pf'}) {
   my $pfId     = $input->{'pfId'};
   my $pf=pf_getRecById($dbh,$pfId);
   if(defined $pf){
       $pfXml=removeDelBook($dbh,$pf->{'xml'});
   }
}
print "Content-type: text/xml\n\n";
print $pfXml;

sub removeDelBook{
    my($dbh,$xml)=@_;
    my $tmp=$xml;
    my $rid=0;
    while($tmp =~ s/<rid>(\d+)<\/rid>//){       
        next if($1 eq '0');
        if(isDeleted($dbh,$1)){
	    $rid=$1;
            $xml =~ s/<rid>$rid<\/rid>/<rid>0<\/rid>/g;
        }
=item        if(isDeleted($dbh,$1)){
            $rid= $1;
            my $bk="";
            while($xml =~ s/(<book>(.*?)<\/book>)//){
                my $b= $1 ;
                if ($b !~ m/<rid>$rid<\/rid>/i) {
                    $bk .= $b;
                }
            }
            $xml =~ s/<\/libraryRs>/$bk\n<\/libraryRs>/;
        }
=cut            
    }
    return $xml;
}

sub isDeleted{
    my($dbh,$rid)=@_;
    my $ret=1;
    my $sth=$dbh->prepare("select rid from opl_item where rid=? && barcode not regexp '^\_\_\_'");
    $sth->execute($rid);
    if(my $r =$sth->fetchrow_hashref){
        $ret=0;
    }
    return $ret;
}
     

