#!/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;
    }

    _saveRecordIdentifier($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 _saveRecordIdentifier {
    my ($dbh, $marc) = @_;

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

    my $subfield_code = {
        '035' => 'a',
        '020' => 'a',
    };

    $dbh->do(<<_SQL_);
delete from opl_recordIdentifier where rid = $rid
_SQL_

    my $sth = $dbh->prepare(<<_SQL_);
insert
into    opl_recordIdentifier
set     rid = ?,
        tag = ?,
        code = ?,
        data = ?
_SQL_

    my ($code, $data, $isbn_obj, $isbn13);
    foreach my $tag (keys %{$subfield_code}) {
        $code = $subfield_code->{$tag};
        foreach my $f ($marc->field($tag)) {
            $data = $f->subfield($code);

            if (!$data) {
                next;
            }
            $data=~ s/^([\D]*)([0-9]+)(.*)/$2/g;
            if ($tag eq '020' && $code eq 'a' && length($data)==10) {
                $isbn_obj = Business::ISBN->new($data) || next;
                $isbn13 = $isbn_obj->as_isbn13;
                $data = $isbn13->as_string([]);
            }
            elsif ($tag eq '035' && $code eq 'a' && 
                    $data !~ m/^\(OCoLC\)[1-9]/) {
                next;
            }

            $sth->execute($rid, $tag, $code, $data);
        }
    }

    $sth->finish;
}
