#!/usr/bin/perl
#
# Qpid 0.10 comes with SWIG generated Perl wrappers for the C++ qpid::messaging API in ./qpid-0.10/cpp/bindings/qpid/perl
# The easiest way to build is just to do a "./bootstrap" "./configure" "make all" "make install" to build the C++
# broker and client API. "make install" installs the libcqpid_perl.so, but doesn't seem to install cqpid_perl.pm
# so this needs to be put manually somewhere on the Perl @INC path or PERL5LIB env variable needs to point to it.
#

use strict;
use warnings;

use cqpid_perl;
use cqpid_perl_utf8;

use Term::ReadKey;


# Unfortunately this falls at the last hurdle as there's no way to set the encoding of the $value. The
# qpid::messaging SWIG binding hides the Variant class and keeps the default binary encoding for strings
#sub utf8EncodeBlock
#{
#	(my $block) = @_;
#	my $bindings = $block->{"x-bindings"};
#	foreach my $binding(@$bindings) {
#		my $arguments = $binding->{"arguments"};
#		while (my ($key, $value) = each(%$arguments)) {
#			print "$key => $value\n";
#		}
#	}
#}

# This method extracts the "node" and "link" Maps from the options part of the Address and passes references
# to them to the utf8EncodeBlock method in order to repair the contents of the block.
#sub utf8EncodeAddress
#{
#	(my $addr) = @_;
#	my $options = $addr->getOptions();
#	my $node = $options->{"node"};
#	if (defined $node) {
#		utf8EncodeBlock($node);
#	}
#
#	my $link = $options->{"link"};
#	if (defined $link) {
#		utf8EncodeBlock($link);
#	}
#	$addr->setOptions($options);		
#	return $addr;
#}


my $broker            = "localhost:5672";
my $address           = "perlconsumer; {create: receiver, node: {x-declare: {arguments: {'qpid.policy_type': ring, 'qpid.max_size': 500000000}}, x-bindings: [{exchange: 'amq.match', queue: 'perlconsumer', key: 'data1', arguments: {x-match: all, data-service: amqp-delivery, item-owner: fadams}}]}}";
my $connectionOptions = "{reconnect: true}";

my $addr = new cqpid_perl::Address($address);
my $utf8addr = cqpid_perl_utf8::utf8EncodeAddress($addr);

my $connection = new cqpid_perl::Connection($broker, $connectionOptions);
eval {
    $connection->open();
    my $session = $connection->createSession();
    my $receiver = $session->createReceiver($utf8addr);
	$receiver->setCapacity(100); # Enable receiver prefetch

	my $key;
	my $i = 0;
	do {
		my $message = new cqpid_perl::Message();
		if ($receiver->fetch($message, $cqpid_perl::Duration::SECOND)) {
			#print $message->getContent() . "\n";

			my $headers = $message->getProperties();
			print $headers->{"item-owner"} . "\n";
			print $headers->{"data-service"} . "\n";

			print "message count = " . $i . ", length = " . $message->getContentSize() . "\n";
			$session->acknowledge();

			$i++;
		} else {
			#print "blah\n";
		}
	} while (not defined ($key = ReadKey(-1)));# keep looping until return key is pressed

	$session->acknowledge();
	$connection->close();
};

die $@ if ($@);
