#!/usr/bin/perl

$REVISION = '$Id: appTest2.pl,v 1.6 2004/06/08 06:51:01 eric Exp $ ';

use strict;

#BEGIN {unshift@INC,('../../..');}
package testRdfParser;
use vars qw(@ISA);

@ISA = qw(W3C::Rdf::RdfApp);

use W3C::Util::Exception;
use W3C::Rdf::RdfApp;
use W3C::Rdf::Atoms qw($ATTRIB_GroundFact);

eval {
    my $tester = new testRdfParser;
    if (0) {
	$tester->prepareParser();
    } else {
	$tester->{XML_PARSER} = new W3C::XML::PerlXmlParser;
	my $errorHandler = new W3C::Rdf::RdfDbErrorHandler(-documentLocator => $tester->{XML_PARSER});
	$tester->{RDF_DB} = new W3C::Rdf::RdfDB({-atomDictionary => $tester->{-atomDictionary}, -errorHandler => $errorHandler, -lazyReification => 1});
	$tester->{RDF_PARSER} = new W3C::Rdf::Parser({-atomDictionary => $tester->{-atomDictionary}, 
						      -nextTrustControlBlock=>1, -trustedIds=>{}, -untrustedIds=>{}, 
						      -rdfDB=>$tester->{RDF_DB}, -namespaceHandler=>undef, 
						      -errorHandler=>$errorHandler, -appendAttribution=>0});
	$tester->{NAMESPACE_HANDLER} = new W3C::XML::NamespaceAndStringHandler({-documentHandler => $tester->{RDF_PARSER}, 
										-errorHandler => $errorHandler, 
										-passUnknownNamespaces => 1, -useSAX2 => 1});
	$tester->{XML_PARSER}->setDocumentHandler($tester->{NAMESPACE_HANDLER});
	$tester->{XML_PARSER}->setErrorHandler($errorHandler);
    }
    $tester->render(\@ARGV);
}; if ($@) {if (my $ex = &catch('W3C::Util::Exception')) {
	die $ex->toString;
#    die $@.' at line '.$tester->{XML_PARSER}->getLineNumber.' column '.$tester->{XML_PARSER}->getColumnNumber;
    } else {
	die $@;
    }
}

sub render {
    my ($self) = @_;

    my $queryHandler = $self->{RDF_DB}->getAlgaeInterface;
    $self->{-queryHandler} = $queryHandler;
    $queryHandler->setParserEnv($self);

    # Exectute algae requested queries.
    my $query = "(slurp '((../test/algaeTest.rdf)) namespace '(t http://t.t/) ask '((t::p2 ?o1 ?o2)) collect '(?o1 ?o2))";
    my ($nodes, $selects, $messages, $proofs) = $queryHandler->algae($query, undef, {-uniqueResults => 1});

    my $outUri = $self->{-atomDictionary}->getUri("file:/stdout/", undef);
    my $outAttribution = $self->{-atomDictionary}->getAttribution($ATTRIB_GroundFact, $outUri, undef, undef, 1, undef, 0);

    require W3C::Util::TableRenderer;
    my $tr = new W3C::Util::TableRenderer(-dataFilter => sub {
	$_ = !$_ ? 'NULL' : 
	$_->isa('W3C::Rdf::Uri') ? '<'.$_->getUri.'>' : 
	$_->isa('W3C::Rdf::String') ? '"'.$_->getString.'"' : 
	$_->isa('W3C::Rdf::BNode') ? '_:g'.$_->getId.'' : 
	$_->isa('W3C::Rdf::Attribution') ? '['.$_->getUri->getUri.']' : 
	&throw(new W3C::Util::Exception(-message => "don't know how to serialize \"$_\""));
    });
    $tr->addHeaders($selects);
    $tr->addData($nodes);
    print $tr->toString."\n";
}

