package Net::MOO;

use warnings;
use strict;

=head1 NAME

Net::MOO - The great new Net::MOO!

=head1 VERSION

Version 0.01

=cut

our $VERSION = '0.01';

=head1 SYNOPSIS

Quick summary of what the module does.

Perhaps a little code snippet.

    use Net::MOO;

    my $foo = Net::MOO->new();
    ...

=cut

my $DEBUG = 0;
my @bosses = ("#85", "#102", "#3570");

sub add_page_action {
    my ($moo,$regexp,$code,$args) = @_;
    push @{$moo->{page_actions}}, [$regexp,$code,$args];
}


sub connect {
    my $class = shift;
    my $moo = new Expect;
    $moo->raw_pty(1);
    $moo->spawn("telnet", "moo.di.uminho.pt", "7777") or die "Cannot spawn telnet";

    $moo->expect(15, '-re', 'D i g i t a');
    $moo->send("co etelvina GELivE\n");
    return bless {expect => $moo, page_actions => []}, $class;
}


sub run {
    my $moo = shift;
    while(1) {
        $moo->{expect}->expect(undef,
                               [ qr/#\$#\s([\w=+']+).*\n(.*\n){2}\s#\$#\send\s\1/ => \&incoming_page, $moo ],
                              );
    }
}


sub incoming_page {
    my $expect = shift;
    my $moo = shift;
    my $emote = shift || 0;
    my $match = $expect->match;
    $match =~ s///g;

    print STDERR "----\n\n$match\n\n----\n" if $DEBUG;

    my ($header, $array, $msg, $end) = split /\n/, $match;

    $header =~ m!#\$\#\s([\w=+']+)\s.*\((#\d+)!;
    my ($op,$id) = ($1,$2);

    $msg =~ s/^\w+\s// if $op eq "page";
    $op = "page" if $op =~ m!^=!;
    $op = "page" if $op =~ m!^'!;

    if ($op eq "page") {
        if (grep {$id eq $_} @bosses) {
            if ($msg eq "!quit") {
                $moo -> page($id, "bye!");
                sleep 1;
                exit
            }
        }

	print STDERR "Processing page with '$msg'\n";

        for my $action (@{$moo->{page_actions}}) {
            my $re = $action->[0];
            if ($msg =~ m!$re!) {
                &{$action->[1]}($moo, $id, $msg, $action->[2]);
                last;
            }
        }
    } elsif ($op =~ m!^\+!) {
        $moo -> emote($id, $msg);
    }
}

sub page {
    my ($moo, $id, $str) = @_;
    $moo -> _send_raw("page $id $str");
}


sub emote {
    my ($moo, $id, $str) = @_;
    $moo -> _send_raw("+$id $str");
}

sub _send_raw {
    my ($moo, $code) = @_;
    $moo->{expect}->send("$code\n");
}











=head1 AUTHOR

ASimoes, C<< <ambs@cpan.org> >>

=head1 BUGS

Please report any bugs or feature requests to
C<bug-net-moo@rt.cpan.org>, or through the web interface at
L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Net-MOO>.
I will be notified, and then you'll automatically be notified of progress on
your bug as I make changes.

=head1 ACKNOWLEDGEMENTS

=head1 COPYRIGHT & LICENSE

Copyright 2007 ASimoes, all rights reserved.

This program is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.

=cut

1; # End of Net::MOO
