#!/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;

binmode STDOUT, ":utf8";

our ($jid, $pw, $inputfile, $redis_host, $redis_port);
require 'config.pl';

warn "# $jid <- $inputfile\n";

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 => $redis_host, port => $redis_port );
my $sub = AnyEvent::Redis->new( host => $redis_host, port => $redis_port );

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

		my $response = '...';

		my $body = $msg->any_body;

		my $channel = join(' ', 'channel', $msg->from);
		$pub->publish( $channel, $body );
		warn "#X<< $channel | $body\n";

		if ( $msg =~ m/!subscribe\s+(\S+)/ ) {

			$sub->psubscribe( "channel $1", sub {
				my ( $message, $from ) = @_;
				return unless $from !~ m/\Q$jid\E/; # skip our messages
				warn "#Q<< $from | $message\n";
				my ( undef, $channal, $user ) = split(/ /,$from,3);
				$cl->send_message( "$channel <$user> $message" => $msg->from, $jid, 'chat' );
			});

			$response = "subscribed to $1";

		}

		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;
   },
);

$cl->start;

$j->wait;
