#!/usr/bin/perl
use strict;

use W3C::Util::Exception qw(&throw &catch &DieHandler);
use XML::SAX::ParserFactory;
use W3C::SPDL::Engine;
use W3C::Util::TableRenderer;

eval {
    local($SIG{"__DIE__"}) = \&DieHandler;
    my $xsd = '../descriptions/AWSECommerceService-SPDL-item.wsdl'; # 'test.xsd';
    my $spat = new W3C::SPDL::Engine();
    $spat->parseDescription($xsd);
    my $query = $ARGV[0] =~ m/\bselect\b/i ? $ARGV[0] : "PREFIX tns: <http://dev.w3.org/cvsweb/perl/modules/W3C/SPDL/descriptions/AWSECommerceService-SAWSDL-item-terms.ttl#>
SELECT ?title ?page WHERE {
_:b tns:id \"0FWYBWB91M5S26YBE382\" ;
    tns:keywords \"".(@ARGV ? join(' ', @ARGV) : 'Weaving')."\" ;
    tns:index \"Books\" ;

    tns:asin ?asin ;
    tns:title ?title ;
    tns:page ?page }";
    print "$query\n";
    my ($rows, $selects, $messages, $statements) = $spat->executeQuery($query);
    binmode (STDOUT, ':utf8');
#    print "$_\n" for ($spat->dumpResultSet(undef));
    if (@$rows) {
	my $renderer = new W3C::Util::TableRenderer();
	$renderer->addHeaders(map {$_->toString} @$selects);
	for (my $row = 0; $row < @$rows; $row++) {
	    $renderer->addData(map {$_ ? $_->toString() : 'NULL'} @{$rows->[$row]});
	}
	print $renderer->toString(), "\n";
    }
}; if ($@) {if (my $ex = &catch('W3C::Util::Exception')) {
	die $ex->toString();
    } else {
	die $@;
    }
}

