package IRCConnector;

use strict;
use Thread::Semaphore;
use Thread::Queue;

use Net::IRC;
use Data::Dumper;

# @@@
# Problem of channel / conf battle
# Check that Zakim is on the channel

# IRC parameters

my $nick = 'WS-Zakim';
my $server = 'localhost';
my $username = 'ws-zakim';
my $port = 6667;
my $channel = '#WS-Zakim';
my $ircname = 'WS-Zakim IRC interface';
my $zakimNick = 'Zakim';
my $debuglevel = 1;
my $debug = $debuglevel . ' ' . __PACKAGE__;
my $debugConn = 0;

# IRC Handlers
sub on_connect {
    my $self = shift;
    &main::print("Connected to IRC");
    $self->{up}->up;
    $self->join($channel);
}

sub on_join {
    my ($self, $event) = @_;
    my $channel = ($event->to)[0];
    &main::debug($debug, 1, "Joined $channel");
    $self->invite($zakimNick, $channel);
}

sub msgToZakim {
    my $self = shift;
    $self->{conn}->privmsg($channel, 'Zakim, ' . join(' ', $_[0]));
    &main::debug($debug, 3, 'Pending: ' . $self->{conn}->{q}->pending());
    &main::debug($debug, 2, "Waiting for value...");
    my $ok = 0;
    my $returnv;
    do {
	$returnv = $self->{conn}->{q}->dequeue();
	&main::debug($debug, 2, "Got: $returnv");
	$returnv =~ s/, $nick$//;
	$ok = 1; # this is naive, as Zakim could be answering another query
    } until ($ok);
    return $returnv;
}

sub stripSorry {
    my ($self, $text) = @_;
    $text =~ s/^sorry, $nick, //;
    return ($text);
}

# IRC connection
sub connect() {
    my $self = shift;

    $self->{irc}->start();
}

sub on_public() {
    my ($self, $event) = @_;
    my $arg = join(' ', $event->args);
    if ($event->nick eq $zakimNick) {
	&main::debug($debug, 2, "Received $arg");
	$self->{q}->enqueue($arg);
    }
}

sub lockUntilUp() {
    my $self = shift;
    $self->{conn}->{up}->down;
}

sub new() {
    my $self = {};
    $self->{irc} = new Net::IRC;
    $self->{irc}->debug($debugConn);
    $self->{conn} = $self->{irc}->newconn(Nick     => $nick,
					  Server   => $server,
					  Username => $username,
					  Port     => $port,
					  Ircname  => $ircname)
	or die "Can't connect to IRC server.\n";
    $self->{conn}->{q} = Thread::Queue->new;
    $self->{conn}->{q}->pending();
    $self->{conn}->add_global_handler('376', \&on_connect);
    $self->{conn}->add_global_handler('public', \&on_public);
    $self->{conn}->add_global_handler('join', \&on_join);
    $self->{conn}->{up} = Thread::Semaphore->new(0);
    bless($self);
    return($self);
}

1;
