# LiMuBai Bot Commands
# Written by Ben Reser < ben@reser.org>
# Adapted from test.pl by dennis taylor <dennis@funkplanet.com>

package LiMuBai::Commands;

use strict;
use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);

require Exporter;
@ISA = qw(Exporter);

@EXPORT = ();
@EXPORT_OK = qw(command_parser);
%EXPORT_TAGS = (all=>[qw(command_parser quit op)]);

$VERSION = '0.1';

use POE::Kernel;
use POE::Session;
use POE::Component::IRC;
use LiMuBai::Utils;

sub command_parser {
  my ($from, $to, $text) = @_[ARG0 .. $#_];
  my ($kernel) = $_[KERNEL];
  
  if ($to =~ /^#/ && $text !~ /^\^/) {
    return 1;
  }
  
  unless (LiMuBai::Utils::match_hostmask($from, '*!?breser@*.brain.org')) {
    return 1;
  }

  $text =~ s/^\^//;
  if (lc($text) eq 'quit') {
    return quit(@_);
  } elsif (lc($text) =~ /^op/) {
    return op(@_);
  } elsif (lc($text) =~ /^deop/) {
    return deop(@_);
  } elsif (lc($text) =~ /^join/) {
    return joinch(@_);
  } elsif (lc($text) =~ /^part/) {
    return part(@_);
  }

  return 1;
}

sub quit {
  my ($kernel) = $_[KERNEL];

  $LiMuBai::Globals::quit = 1;
  $kernel->post( 'limubai', 'quit', 'The poison got me!' );
}

sub op {
  my ($from, $to, $text) = @_[ARG0 .. $#_];
  my ($kernel) = $_[KERNEL];

  my($fromnick) = LiMuBai::Utils::get_nick($from);
  my(@args) = split /\s+/, $text;

  unless (defined($args[1]) && $args[1] =~ /^#.*/) {
    if ($to->[0] =~ /^#/ && @{$to} == 1) {
      splice(@args, 1, 2, $to->[0], $args[1]);
    } else {
      return 1;
    }
  }

  unless (defined($args[2])) {
    $args[2] = $fromnick;
  }

  $kernel->post( 'limubai', 'mode', $args[1], '+o', $args[2]);
}

sub deop {
  my ($from, $to, $text) = @_[ARG0 .. $#_];
  my ($kernel) = $_[KERNEL];

  my($fromnick) = LiMuBai::Utils::get_nick($from);
  my(@args) = split /\s+/, $text;

  unless (defined($args[1]) && $args[1] =~ /^#/) {
    if ($to->[0] =~ /^#/ && @{$to} == 1) {
      splice(@args, 1, 2, $to->[0], $args[1]);
    } else {
      return 1;
    }
  }

  unless (defined($args[2])) {
    $args[2] = $fromnick;
  }

  $kernel->post( 'limubai', 'mode', $args[1], '-o', $args[2]);
}

sub joinch {
  my ($from, $to, $text) = @_[ARG0 .. $#_];
  my ($kernel) = $_[KERNEL];
 
  my (@channels) = split /\s+/, $text;
 

  $kernel->post( 'limubai', 'join', @channels[1 .. $#channels]);
}

sub part {
  my ($from, $to, $text) = @_[ARG0 .. $#_];
  my ($kernel) = $_[KERNEL];
  my (@args) = split /\s+/, $text;

  # i.e. no channel name passed
  if (scalar(@args) == 1) {
    if ($to->[0] =~ /^#/ && @{$to} == 1) {
      push @args, $to->[0];
    } else {
      return 1;
    }
  }

  $kernel->post( 'limubai', 'part', @args[1 .. $#args]);
  
}

1;
