#!/usr/bin/perl -w

=item
#!/usr/bin/perl -w
command to update all the sites:
for i in `ls /etc/opals/conf/`; do cp -p /www/opals/script/update_restoreTitle /tmp/urt; perl -pi -e "s/_MY_SITE_/$i/" /tmp/urt; sudo /tmp/urt; done
=cut

use strict;
use DBI;
#use Getopt::Std;
#use CGI;
use lib '/www/opals/module';
use Opals::Context("/etc/opals/conf/opals");

use POSIX qw(
    ceil
);
use Opals::Date qw(
 date_f005
);

use Opals::MarcXml qw(
    mxml_retrieveMarcXml
    mxml_update
);

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

$| = 1;


# Codes start...


#////////////////////////////////////////////////////////////////////////////
my $dateToday= date_f005();
    $dateToday =~ s/([\d]{4})([\d]{2})([\d]{2})[\d]+\.(0|1)/$1-$2-$3/;
my ($rid,$title,$barcode,$onDate,$xml) = (-1,'','','','');
    $rid     = &promptUser("\n\n\x1b\x5b0;49;34m Enter the record id \x1b\x5b2;49;32m");
   # $onDate  = &promptUser("Enter the modified date ", $dateToday);
   # print "rid:   $rid\n";
   # print "onDate:   $onDate\n";
    my $tryEnterRid=0; my $archRs =();
    $rid = checkValidUserInput($rid);
    if($tryEnterRid>2){
       print "\x1b\x5b0;49;30m Sorry. Bye  \n" ;
    }
    exit if($tryEnterRid >2);
   
    $archRs = mxml_retrieveMarcXml($dbh,{rid=>$rid ,onDate=>$onDate});
    if (scalar(@$archRs) <1 ){
        print "\x1b\x5b0;49;30m Sorry. Cannot find MARC XML  for this record id. \n" ;
        $tryEnterRid=3;
    }
    exit if($tryEnterRid >2);
     
    my ($num,$maxNum ) = (0,0);
    my $userConfirm = 'n';
    while (lc($userConfirm) =~ m/n|no/){
        $num =0;
        $userConfirm = userSelectProcess($userConfirm);
    }

    if(lc($userConfirm) =~ m/c|q|cancel|quit/){
        print "\x1b\x5b2;49;31m You did stop proccess to restore record. Bye!\n";
    }
    else{
        if ($xml ne ''){
           print "\x1b\x5b2;49;34m Processing ... Please wait.\n";
           $xml =~ s/[\s]*<subfield code="-">.*<\/subfield>//g;
           $xml =~ s/[\s]*<subfield code="+">.*<\/subfield>//g;
           
           my $bcList = getBarcodeList($dbh,$rid,$xml);
           $rid = mxml_update($dbh,{rid=>$rid, marcXml=>$recXml,bcList=>$bcList});
           
           print "\x1b\x5b2;49;34m Done !\n";
        }
        else{
            print "\x1b\x5b2;49;31m Sorry. Marc XML is emplty!\n";
        }
    }
#////////////////////////////////////////////////////////////////////////////
sub  checkValidUserInput{
    my($uInput) = @_;
    $tryEnterRid += 1 if($uInput !~ m/^-?\d+$/g);
    while ($tryEnterRid >0 && $tryEnterRid <3){
        $uInput   = &promptUser("\x1b\x5b2;49;31m ERROR: Invalid enter! Reenter the valid record id \x1b\x5b2;49;32m");
        if($uInput !~ m/^-?\d+$/g){
            $tryEnterRid += 1;
        }
        else{
            last;
        }
    }
    return $uInput;
}

#////////////////////////////////////////////////////////////////////////////
sub userSelectProcess {
    my($uConf) = @_;

    print "\x1b\x5b0;49;30m Please type a number to select from the following available MARC xml on date:\n";
    foreach my $a (@$archRs){
        print  " " , ++$num,":   $a->{'onDate'} \n";
    }
    $maxNum = $num;
    # prompt for user's choice
    my $selNum = &promptUser("\x1b\x5b0;49;34m Enter  selection \x1b\x5b2;49;32m");
    
    my $error =0 ;
    $error = 1  if($selNum !~ m/^-?\d+$/g);
    $error = 1  if(!$error && ($selNum <1 || $selNum > $maxNum));
    while ($error){
        $error =0 ;
        $selNum = &promptUser("\x1b\x5b2;49;31m ERROR: Invalid enter! Please type a valid number\x1b\x5b2;49;32m");
        $error = 1  if($selNum !~ m/^-?\d+$/g);
        $error = 1  if(!$error && ($selNum <1 || $selNum > $maxNum));
    }
    my $selNum = int( $selNum );

    $onDate = @$archRs[$selNum-1]->{'onDate'};
    $xml    = @$archRs[$selNum-1]->{'marcXml'};
    # prompt for user's answer
    my $ans ='n';
    printf("%s", "\x1b\x5b0;49;34m Do you want to view MARC record:(y/n) \x1b\x5b2;49;32m");
    $ans = <STDIN>;
    while( $ans !~ m/^y|yes|n|no$/g){
       printf("%s", "\x1b\x5b0;49;34m Invalid enter! Please type y or n: \x1b\x5b2;49;32m");
       $ans = <STDIN>;
    }  
    if(lc($ans) =~ m/^y|yes$/g){ 
        print ("\n\x1b\x5b0;49;33m$xml \n");
    }
    printf("\n%s", "\x1b\x5b0;49;34m Do you want to restore now. \x1b\x5b0;49;30m(Type \x1b\x5b1;49;31m y \x1b\x5b0;49;30m to restore/ type \x1b\x5b1;49;31m n \x1b\x5b0;49;30m to select other / type \x1b\x5b1;49;31m q \x1b\x5b0;49;30m to quit).\x1b\x5b2;49;32m  ");
    $uConf =  <STDIN>;
    while( $uConf !~ m/^y|yes|n|no|q|quit$/){
        printf("\n%s", "\x1b\x5b0;49;34m Invalid enter! Please type \x1b\x5b1;49;31m y \x1b\x5b0;49;30m or \x1b\x5b1;49;31m n \x1b\x5b0;49;30m or \x1b\x5b1;49;31m q.\x1b\x5b2;49;32m  ");
        $uConf =  <STDIN>;
    }

    printf("\x1b\x5b0;49;32m\n");
    return $uConf;
}
#////////////////////////////////////////////////////////////////////////////
sub promptUser {
   my( $promptString, $defaultValue) = @_;

   if ($defaultValue) {
      print $promptString, "'", $defaultValue, "': ";
   } else {
      print $promptString, ": "; 
   }

   $| = 1;               # force a flush after our print
   $_ = <STDIN>;         # get the input from STDIN (presumably the keyboard)

   chomp;

    if ($defaultValue) {
      return $_ ? $_ : $defaultValue;    # return $_ if it has a value
   } else {
      return $_;
   }
}
#////////////////////////////////////////////////////////////////////////////
sub isOnLoan{
    my ($dbh,$barcode)= @_;
    my $sth = $dbh->prepare("select idloan from opl_loan where barcode=?  && dateReturn is null");
    $sth->execute($barcode);
    my ($rec) = $sth->fetchrow_hashref;
    $sth->finish;
    return ($rec)? $rec->{'idloan'}:0;    
}

#////////////////////////////////////////////////////////////////////////////

sub getBarcodeList {
    my ($dbh,$rid,$recXml) = @_;
    my @barcodeNew =();
    my $bcList={};
    while ($recXml =~ s/([\s]*<datafield tag="852" ind1="[\d ]" ind2="[\d ]">([\s]*<subfield code="[\w\-]">.*<\/subfield>)+[\s]*<\/datafield>)//) {
        my $tmp852 =$1;
        if ($tmp852 =~ m/<subfield code="p">(.*)<\/subfield>/) {
            $bcList->{$1}={status=>"new"};
            push @barcodeNew ,$1;
        }
    }
    my $sql = " select  barcode  from opl_item
                where   rid = ? && substring(barcode, 1, 3) <> '___' ";
    my $bcListStr=  join("','"@barcodeNew );            
    $sql .= " &&  barcode not in ('$bcListStr')" if ($bcListStr ne '');            
    my $sth = $dbh->prepare($sql);
    $sth->execute($rid);
    while (my ($bc) = $sth->fetchrow_array) {
        next if (isOnLoan($dbh,$bc));
        $bcList->{$bc}={status=>"delete"};
    }

    $sth->finish; 
    return $bcList;
}





