################################
# Filter Module                #
################################

# The canonical filters should be installed on your path somewhere.
# You can get the source from these from your local distributor.

package BotModules::Filter;
use vars qw(@ISA);
use IPC::Open2;
@ISA = qw(BotModules);
1;

my @Filters = (
    'b1ff',
    'chef',
    'cockney',
    'eleet',
    'jethro',
    'jibberish',
    'jive',
    'kraut',
    'nyc',
    'rasterman',
    'upside-down',
);

sub Help {
    my $self = shift;
    my ($event) = @_;
    my $reply = {
        '' => 'This module is an interface to the text filter applications.',
    };
    foreach (@Filters) {
        $reply->{$_} = "Pass the text through the $_ filter. Syntax: $_ <text>";
    }
    if ($self->isAdmin($event)) {
        $reply->{'filtersay'} = "Pass text through a filter and send it to a channel. Syntax: filtersay <filter> <channel> <text>";
    }
    return $reply;
}

sub Told {
    my $self = shift;
    my ($event, $message) = @_;
    foreach (@Filters) {
        if ($message =~ /^\s*\Q$_\E\s+(.+?)\s*$/si) {
            $self->spawnChild($event, sub { return $self->Filter(@_); }, [$_, $1], 'filter', []);
            return 0; # we've dealt with it, no need to do anything else.
        } elsif (($message =~ /^\s*filtersay\s+\Q$_\E\s+(\S+)\s+(.+?)\s*$/si) and ($self->isAdmin($event))) {
            $self->spawnChild($event, sub { return $self->Filter(@_); }, [$_, $2], 'filter', [$1]);
            return 0; # we've dealt with it, no need to do anything else.
        }
    }
    return $self->SUPER::Told(@_);
}

sub Filter {
    my $self = shift;
    my($filter, $text) = @_;
    my $reader;
    my $writer;
    local $/ = undef;
    my $pid = open2($reader, $writer, $filter);
    print $writer $text;
    close($writer);
    my $reply = <$reader>;
    close($reader);
    waitpid($pid, 0);
    return $reply;
}

# ChildCompleted - Called when a child process has quit
sub ChildCompleted {
    my $self = shift;
    my ($event, $type, $output, @data) = @_;
    if ($type eq 'filter') {
        local $event->{'target'} = $data[0] if defined($data[0]);
        $self->say($event, $output);
    } else {
        return $self->SUPER::ChildCompleted(@_);
    }
}