package Orangutan::Monkeys;

use strict;

sub new {
    my $class = shift;
    my $self = { };
    $self->{'monkeys'} = { };
    bless $self, $class;
    return $self;
}

sub Init($) {
    my $self = shift;
    foreach my $monkey ($main::config->Monkeys) {
        my $jid = $main::config->Get('monkeys', $monkey->GetID);
        if (!defined($self->{'monkeys'}->{$jid})) {
            $self->{'monkeys'}->{$jid} = [ ];
        }
        push(@{$self->{'monkeys'}->{$jid}}, $monkey);
    }
}

sub Exists($$) {
    my ($self, $jid) = @_;
    if (defined($self->{'monkeys'}->{$jid})) {
        return $self->{'monkeys'}->{$jid}[0]->GetID;
    } else {
        return undef;
    }
}

sub Handle($$$) {
    my ($self, $jid, $message) = @_;
    foreach my $monkey (@{$self->{'monkeys'}->{$jid}}) {
        my @matches = $monkey->Match($message);
        if (scalar @matches > 0) {
            $monkey->CallHandler(@matches);
            return;
        }
    }
}

1;
