#!/usr/bin/perl
# Thu, Apr 14, 2011 @ 10:40:38 EDT
# UPDATE FILE:/www/odev/bin/marc21/edit 
#
#
#

#use utf8;
use strict;
use CGI;

use Opals::Context;
use Date::Calc qw(Day_of_Week Week_Number Day_of_Year);

use Opals::MarcXml qw(
    mxml_retrieveMarcXml
);
use Opals::Date qw(
    date_f005
);

use Opals::Template qw(
    tmpl_read
    tmpl_write
    tmpl_rangedPageList
);
use Opals::Locale qw(
    loc_getMsgFile
    loc_write
);



my $dbh = Opals::Context->dbh();
END { $dbh->disconnect(); }

my $cgi = CGI->new;
my $input = $cgi->Vars();
 

my ($permission, $cookie, $template) = tmpl_read(
        {
            dbh             => $dbh,
            cgi             => $cgi,
            tmplFile        => 'report/archiveRecord.tmpl',
            reqPermission   => 'marc_edit|rpt_catRec',
        }
);

    my $kw= $input->{'kw'};
    my $sf= $input->{'sf'};
    my $op= $input->{'op'};
       $op = 'search' if(!$op ||  $op eq '');
       $sf = 'barcode' if($sf eq '');
    my $rOpt='';
    my $rid = $kw;
    $rOpt = 'override' if($rOpt eq '');


    if($op eq 'search' && $kw ne ''){
        $rid    = getRecordId($dbh,$kw) if($sf eq 'barcode');
        my $archRs = mxml_retrieveMarcXml($dbh,{rid=>$rid ,onDate=>''});
        $template->param( "sf_$sf"  => 1,
                          sf        => $sf);


        if(ref($archRs) eq "ARRAY" && scalar(@{$archRs})>0){
            $template->param(
                rid     => $rid,
                archRs  => $archRs);
        }
        else{
            $template->param(noArchXml => 1);
        }
    }
    elsif($op eq 'restore'){
        my $archId = $input->{'archId'}; 
           $rOpt   = $input->{'rOpt'};
           $rOpt = 'override' if($rOpt eq '');

        my $sql = " select  rid,UNCOMPRESS(marcXml) as marcXml from  opl_recordArchive where archId = $archId ";
        my $sth = $dbh->prepare($sql);
        $sth->execute();

        if(my ($rid,$xml) = $sth->fetchrow_array){
            my $curMarc = '';
            
        }
        $sth->finish;
        $template->param(
           rOpt         => $rOpt,
           "rOpt_$rOpt" => 1,
        );
    }


$template->param(kw => $kw,"sf_$sf"  => 1,"rOpt_$rOpt" => 1,
                 hlpUrl     => Opals::Constant->getHlpUrl('archiveRecord'));
my $msgValMap ={};
my $msgMap            =loc_getMsgFile('report/reports.msg',$msgValMap);
loc_write($template,$msgMap);

tmpl_write($dbh, $cgi, $cookie, $template);


################################################################################
sub getRecordId{
    my ($dbh,$kw) = @_;
    $kw =~ s/^\s+|\s+$//g;
    my $sth = $dbh->prepare("select rid from opl_item where barcode regexp '^\_\_\_$kw' OR barcode  = '$kw' ");
    $sth->execute() || return 0;
    my ($rid) = $sth->fetchrow_array();
    $sth->finish;
    return $rid;
}

################################################################################
  
