#!/usr/bin/perl
use warnings;
use strict;
use utf8;
use AnyEvent;
use AnyEvent::XMPP::Client;
use AnyEvent::XMPP::Ext::Disco;
use AnyEvent::XMPP::Ext::Version;
use AnyEvent::XMPP::Namespaces qw/xmpp_ns/;
use AnyEvent::Redis;
use Data::Dump qw(dump);
use Encode;
use Carp qw(confess);

binmode STDOUT, ":utf8";

my $jid = $ENV{XMPP_JID} || die "XMPP_JID";
my $pw  = $ENV{XMPP_PASSWD} || die "XMPP_PASSWD";

my $j       = AnyEvent->condvar;
my $cl      = AnyEvent::XMPP::Client->new (debug => 1);
my $disco   = AnyEvent::XMPP::Ext::Disco->new;
my $version = AnyEvent::XMPP::Ext::Version->new;

$cl->add_extension ($disco);
$cl->add_extension ($version);

$cl->set_presence(undef, 'I\'m a talking bot.', 1);

$cl->add_account ($jid, $pw);
warn "connecting to $jid...\n";

my $pub = AnyEvent::Redis->new( host => $ENV{REDIS_HOST}, port => $ENV{REDIS_PORT}, on_error => sub { confess @_ } );
my $sub = AnyEvent::Redis->new( host => $ENV{REDIS_HOST}, port => $ENV{REDIS_PORT}, on_error => sub { confess @_ } );

our $contacts;

$sub->psubscribe( 'channel *', sub {
	my ( $message, $from ) = @_;
	return unless $from !~ m/\Q$jid\E/; # skip our messages
	Encode::_utf8_on($message);
	warn "#Q<< ", dump( $from, $message );
	my ( undef, $channel, $user ) = split(/ /,$from,3);
warn "# contacts ",dump($contacts);
	foreach my $contact ( keys %$contacts ) {
		next if $from =~ m/\Q$contact\E/;
		warn "# $jid [$from] -> [$contact] | $message\n";
		$cl->send_message( join(' ',$channel, $user, $message), $contact => $jid, 'chat' );
	}
});

$cl->reg_cb (
   session_ready => sub {
      my ($cl, $acc) = @_;
      warn "connected!\n";
   },
   message => sub {
		my ($cl, $acc, $msg) = @_;

		my $body = $msg->any_body;

		my $f = $msg->from;
		$f =~ s!/.+!!;
		$contacts->{ $f }++;

warn "# contacts ",dump($contacts);

		my $channel = join(' ', 'channel', $msg->from);
		Encode::_utf8_off($body);
		$pub->publish( $channel, $body );
		warn "#X<< ",dump($channel, $body);

#		my $repl = $msg->make_reply;
#		$repl->add_body( $response );
#		$repl->send;
#		warn "#>>> $response\n";

   },
   contact_request_subscribe => sub {
      my ($cl, $acc, $roster, $contact) = @_;
      $contact->send_subscribed;
      warn "Subscribed to ".$contact->jid."\n";
   },
   error => sub {
      my ($cl, $acc, $error) = @_;
      warn "Error encountered: ".$error->string."\n";
      $j->broadcast;
   },
   disconnect => sub {
      warn "Got disconnected: [@_]\n";
      $j->broadcast;
   },
	roster_update => sub {
		my ($con,$account,$roster) = @_;
warn "XXXXX", ref($account), " | ", ref($roster);
		foreach my $contact ( $roster->get_contacts ) {
			$contacts->{ $contact->{jid} }++;
			warn "# contacts ",dump($contacts);
		}
		warn "# contacts ",dump($contacts);
	},
);

$cl->start;

$j->wait;
