#!/usr/bin/perl -w

use strict;
use Business::ISBN;
use MARC::Record;
use MARC::Field;

use lib "/www/opals/module";
use Opals::Context("/etc/opals/conf/_SITECODE_");
use Opals::Context;
use Opals::Marc::Record;
use Opals::Utility qw(
    util_getXmlRecord
);

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

$| = 1;
# Codes start...

my $sth = $dbh->prepare(<<_SQL_);
select  distinct rid
from    opl_item
where barcode not regexp '^\_\_\_'
order by rid asc
_SQL_

$sth->execute() || die "ERROR: Cannot get RIDs.\n";
my $marc;
while (my ($rid) = $sth->fetchrow_array()) {
    print "$rid\n";
    $marc = _getRecordByRid($rid);
    if (!$marc) {
        next;
    }

    _saveRecordISBN($dbh, $marc);
}

$sth->finish;

# Codes end.

exit 0;
################################################################################


sub _getRecordByRid {
    my ($rid) = @_;

    my $xml = util_getXmlRecord($rid) || return;
    my $marc = Opals::Marc::Record::newFromXml($xml);

    return $marc;
}
############################################################


sub getRidFromMarc {
    my ($marc) = @_;

    if (!$marc) {
        return;
    }

    my $f001 = $marc->field('001');
    if (!$f001) {
        return;
    }

    return $f001->data();
}
############################################################


sub _saveRecordISBN {
    my ($dbh, $marc) = @_;

    my $rid = getRidFromMarc($marc) || return;

    my $sth = $dbh->prepare(<<_SQL_);
update opl_marcRecord
set     isbn=?
where    rid = ?
_SQL_

        foreach my $f ($marc->field('020')) {
            my $data = $f->subfield('a');
            if (!$data) {
                $data = $f->subfield('z');
            }
            next if(!$data);
            $data=~ s/^([\D]*)([0-9]+)(.*)/$2/g;
            $sth->execute( $data,$rid);
            last;
        }

    $sth->finish;
}
