#!/opt/perl/bin/perl
use strict;
use utf8;
use Event;
use AnyEvent;
use XML::Twig;
use Net::XMPP2 qw/xep-86/;
use Net::XMPP2::Client;
use Encode;

sub dumpxml {
   my $data = shift;
   my $t = XML::Twig->new;
   if ($t->safe_parse ("<deb>$data</deb>")) {
      $t->set_pretty_print ('indented');
      $t->print;
      print "\n";
   } else {
      print "[$data]\n";
   }
}

binmode STDOUT, ":utf8";

my $j = AnyEvent->condvar;

my $cl = Net::XMPP2::Client->new;
$cl->add_account (@ARGV);
$cl->reg_cb (
   connected => sub {
      $cl->send_message ("Hello!" => 'elmex@jabbfer.org');
      0
   },
   roster_update => sub {
      my ($cl, $acc, $roster, $contacts) = @_;
      $roster->debug_dump;
      $acc->connection ()->send_presence ('probe' => undef, to => 'elmex@jabfber.org');
      print "OEOFWEFIEJWFEWO\n" if not $roster->is_retrieved;
      1
   },
   presence_update => sub {
      my ($cl, $acc, $roster, $contact, $old, $new) = @_;
      $roster->debug_dump;
      1
   },
   sasl_error => sub {
      my ($cl, $acc, $error) = @_;
      print "SASL ERROR".$error->string."\n";
   },
   presence_error => sub {
      my ($cl, $acc, $error) = @_;
      print "PRESENCE ERROR: " .  $error->string . "\n";
      1;
   },
   message_error => sub {
      my ($cl, $acc, $error) = @_;
      print "MESSAGE ERROR: " .  $error->string . "\n";
      1;
   },
   disconnect => sub { warn "DISCON[@_]\n"; 1 },
   debug_send => sub {
      warn "send: @_\n";
      1
   },
   debug_recv => sub {
      warn "recv: @_\n";
      1
   },
);

$cl->reg_cb (contact_request_subscribe => sub {
   my ($cl, $acc, $roster, $contact, $rdoit) = @_;
   $$rdoit = 1;
   $contact->send_subscribe;
   1
});

$cl->reg_cb (contact_did_unsubscribe => sub {
   my ($cl, $acc, $roster, $contact, $rdoit) = @_;
   $$rdoit = 1;
   1
});

$cl->reg_cb (roster_update => sub {
   my ($cl, $acc, $roster, $contacts) = @_;

  $roster->debug_dump;
  # $roster->new_contact ('elmex@jabber.org', 'Der elmex', ['ABC', 'TEst'], sub {
  #    $roster->get_contact ('elmex@jabber.org')->send_subscribe;
  #    $roster->delete_contact ('elmex@jabber.org');
  # });
  #$cl->remove_accounts ("TEST");

   0
});

$cl->start;

$j->wait;
