#!/usr/bin/perl

#use utf8;
use strict;
use CGI;
use JSON;
use Opals::Constant;
use Opals::Context; 
use Opals::Utility qw(util_getXmlRecord);
use Opals::MarcXml qw(
    mxml_update 
    mxml_updateItemStatus
    mxml_updateItemType
    mxml_delSubfield    
    mxml_addSubfield
);
use Opals::Transaction qw(
    trans_doReverseLost
);

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

my $loginuid = $ENV{'curUserId'};

my $itemTypeInfo ={};
if ($ENV{'REQUEST_METHOD'} eq "POST") {
    my $json ="";
    while (<STDIN>) {
        $json .= $_;
    }
    $itemTypeInfo = decode_json($json);
    my ($rid,$barcode,$status,$itemType,$nonPubNotes)= ($itemTypeInfo->{'rid'},$itemTypeInfo->{'barcode'},
                                           $itemTypeInfo->{'newStatus'},$itemTypeInfo->{'newItemType'},$itemTypeInfo->{'nonPubNotes'});

    if(defined $status && $status ne''){
        my $curStatus=getItemCurStatus($dbh,$barcode);
        if(defined $curStatus && $curStatus == ITEM_LOST && $status==ITEM_ACTIVE){
             trans_doReverseLost($dbh,$barcode,$loginuid);
        }
        mxml_updateItemStatus($dbh,$barcode,$status);
    }
    my $xml=undef;
    if(defined $itemType && $itemType ne''){
        $xml=util_getXmlRecord($rid);
        mxml_updateItemType($xml,{newType=>$itemType,bcList=>[$barcode]});
    }
    if(defined $nonPubNotes ){
        $xml = util_getXmlRecord($rid) if(!defined $xml);
        $xml = mxml_delSubfield($xml,{tag =>'852',code=>'x',bcList=>[$barcode]});
        foreach my $sf852x (@$nonPubNotes){
            $xml=mxml_addSubfield($xml,{tag =>'852',code=>'x',bcList=>[$barcode],data=>$sf852x,opt=>1});
        }
    }
    if(defined $xml){
         mxml_update($dbh, {rid=>$rid, marcXml=>$xml});
    }
}
print "Content-type: text/plain\n\n";
print  to_json({status=>1});

#=======================================================================

sub updateItemType{
    my($dbh,$rid,$barcode,$newType)=@_;
    my $xml=util_getXmlRecord($rid);
    if($xml && $xml ne ""){
        my $marc = Opals::Marc::Record::newFromXml($xml);

        foreach my $f852 ( $marc->field('852') ) {
            if($f852->subfield('p') eq $barcode){
                $f852->delete_subfield(code => '3');
                $f852->add_subfields('3'=>$newType);
                last;
            }
        }
        $xml = MARC::File::XML::record($marc);
        mxml_update($dbh, {rid=>$rid, marcXml=>$xml});
    }

}
#=======================================================================

sub getItemCurStatus{
    my($dbh,$barcode)=@_;
    my ($status)=$dbh->selectrow_array("select status from opl_itemstatus where barcode='$barcode' order by id desc limit 1");
    return $status;
}

