package EPrints::Plugin::Sword::Import::Broker_Common;

# Common routines for the various Broker_* systems
# Much of it is for the NLM-DTD formatted stuff.

use strict;
use EPrints::Plugin::Sword::Import;

our @ISA = qw/ EPrints::Plugin::Sword::Import /;

my $DEBUG = 0;

############################
#
# All database queries are handled here.
# As EPrints loads Apache::DBI, our "new connection" is actually
# just re-using an exisiting one.
#
############################
sub query_db
{
    my $statement = shift;

    return undef unless $statement;

    my ($dbh, $error, $dbreturn_ref);

    eval {
        $dbh = DBI->connect(
                            "dbi:Pg:dbname=oarj;host=localhost",
                            'oarj',
                            'cramPlink?',
                            {AutoCommit => 0, PrintError => 0, RaiseError => 0}
                           );
    };
    if ($@)
    {
        $error = "Unable to connect to database because $@";
    }
    else
    {

        eval { $dbreturn_ref = $dbh->selectall_arrayref($statement); };
        if ($@)
        {
            $error = "Transaction aborted because $@";
        }
        eval { $dbh->rollback; };

    } ## end else [ if ($@) ]
    if ($error)
    {
        return (0, $error);
    }
    else
    {
        return (1, $dbreturn_ref);
    }
} ## end sub query_db

sub new
{
    my ($class, %params) = @_;

    my $self = $class->SUPER::new(%params);

    $self->{name}    = "Common routines for the Broker Sword importes";
#    $self->{visible} = "none";
    return $self;
} ## end sub new

sub extract
{
    my ($plugin, $tag, $key, $node, $epdata) = @_;

    my $element = $node->getElementsByTagName($tag)->item(0);
    $epdata->{$key} = $plugin->strip_xml($element, $tag) if defined $element;

    print STDERR "'$tag' => '$key' = '" . $epdata->{$key} . "'\n"
      if $DEBUG && defined($element);
} ## end sub extract

sub extract_with_attr
{
    my ($plugin, $tag, $key, $attr_key, $attr_value, $node, $epdata) = @_;
    foreach my $element ($node->getElementsByTagName($tag))
    {
        next unless $element->getAttribute($attr_key) eq $attr_value;
        $epdata->{$key} = $plugin->strip_xml($element, $tag)
          if defined $element;
        print STDERR
          "'$tag\[$attr_key=$attr_value]' -> '$key' = '$epdata->{$key}'\n"
          if $DEBUG;
    } ## end foreach my $element ($node->getElementsByTagName...)
} ## end sub extract_with_attr

sub strip_xml
{
    my ($plugin, $node, $tag) = @_;

    my $xml_string = $node->toString;
    $xml_string =~ s/^<$tag>\n?//;      # leading tag
    $xml_string =~ s/\n?<\/$tag>$//;    # trailing tag

    # convert into html
    #   $xml_string =~ s/<(\/?i)talic>/<$1>/g; # turn <italic> into html <i>
    #   $xml_string =~ s/<p[^>]*>/<p>/g; #Ā turn <p id="x"> into <p>

    # convert into plain text
    $xml_string =~ s/<(\/?)italic>//g;
    $xml_string =~ s/<p[^>]*>//g;
    $xml_string =~ s/<sup>/^/g;
    $xml_string =~ s/<\/sup>//g;

    # convert xml entities into unicde characters
    # &#x000d7; => × (rather than x)
    $xml_string =~ s/&#x([0-9a-f]+);/chr(hex($1))/ige;

    $xml_string =~
      s/<label>[0-9]+<\/label>//g;  # don't want internal cross referencing info
    $xml_string =~ s/<\/?[^>]+>/ /g;    # dangerously strip out html tags
    $xml_string =~ s/ +/ /g;            # collapse multiple spaces

    # decode < and > there may also be other entities
    $xml_string =~ s/&lt;/</g;
    $xml_string =~ s/&gt;/>/g;

    # trim off leading and trailing carriage returns and spaces
    $xml_string =~ s/^[\n\t ]+//;
    $xml_string =~ s/[\n\t ]+$//;

    return $xml_string;
} ## end sub strip_xml

1;
