#!/usr/bin/perl -w

use strict;

use Net::XMPP;
use Carp;

our $verbose = 0;

my $host = shift;
my $username = shift;
my $password = shift;

my $client = new Net::XMPP::Client();

$client->SetCallBacks(message => \&message);

$client->Connect(hostname => $host);

my @result = $client->AuthSend(username => $username,
			       password => $password,
			       resource => 'Pong');

print join(', ', @result), "\n";

croak $result[0] if $result[0] ne 'ok';

print "Connected\n";

$client->PresenceSend();

print "Sent presence\n";

our @toAnswer;
while(defined(my $status = $client->Process())) {
    print "Processing ($status)\n" if $verbose;

    while(defined(my $ping = shift @toAnswer)) {
	my($session, $seq, $to) = @$ping;
	print "Answer ping $session/$seq from $to\n";

	my $msg = new Net::XMPP::Message();
	$msg->SetMessage(to => $to,
			 body => "Pong $session/$seq!");
	$client->Send($msg);
    }
}

print "ERROR: The connection was killed...\n";

sub message
{
    my $sid = shift;
    my $message = shift;

    my $type = $message->GetType();
    my $fromJID = $message->GetFrom("jid");
#    my $from = $fromJID->GetUserID();
    my $from = $message->GetFrom();
    my $resource = $fromJID->GetResource();
    my $subject = $message->GetSubject();
    my $body = $message->GetBody();

    if ($verbose) {
	print "===\n";
	print "Message ($type)\n";
	print "  From: $from ($resource)\n";
	print "  Subject: $subject\n";
	print "  Body: $body\n";
	print "===\n";
	print $message->GetXML(),"\n";
	print "===\n";
    }

    if($body =~ /^Ping (\d+)\/(\d+)!$/) {
	push @toAnswer, [$1, $2, $from];
    }
}
