# By Stefan 'tommie' Tomanek
use strict;

use vars qw($VERSION %IRSSI);
$VERSION = "20100713";
%IRSSI = (
    authors     => "Stefan 'tommie' Tomanek, Frank 'yogan' Blendinger",
    contact     => "stefan\@pico.ruhr.de, fb\@intoxicatedmind.net",
    name        => "CRAPbuster",
    description => "Removes lines with certain levels or matching regex from your buffer",
    license     => "GPLv2",
    changed     => "$VERSION",
    commands    => "crapbuster{-levels|-regex} [LINES-LIMIT] {LEVELS|REGEX}"
);

use Irssi;
use Irssi::TextUI;

sub cmd_crapbuster_levels ($$$) {
    my ($args, $server, $witem) = @_;
    my $limit = -1;
    if ($args =~ m/^\s*(\d+)\b\s*(.*)$/) {
        $limit = $1;
        $args = $2;
    }
    crapbuster_levels($limit, $args, $server, $witem);
}

sub cmd_crapbuster_regex ($$$) {
    my ($args, $server, $witem) = @_;
    my $limit = -1;
    if ($args =~ m/^\s*(\d+)\b\s*(.*)$/) {
        $limit = $1;
        $args = $2;
    }
    crapbuster_regex($limit, $args, $server, $witem);
}

sub crapbuster_levels ($$$$) {
    my ($limit, $levels, $server, $witem) = @_;
    $levels = "CRAP CLIENTCRAP" unless $levels;
    my $win = ref $witem ? $witem->window() : Irssi::active_win();
    my $view = $win->view;
    my $line = $view->get_lines;
    $line = $line->next while defined $line->next;
    while (defined $line){
        last if $limit == 0;
        my $level = $line->{info}{level};
        my $copy = $line;
        $line = $line->prev;
        foreach (split / /, $levels) {
            next unless ($level == Irssi::level2bits($_));
            $view->remove_line($copy);
            last;
        }
        $limit-- if $limit;
    }
    $view->redraw();
}

sub crapbuster_regex ($$$$) {
    my ($limit, $regex, $server, $witem) = @_;
    return unless $regex;
    my $win = ref $witem ? $witem->window() : Irssi::active_win();
    my $view = $win->view;
    my $line = $view->get_lines;
    $line = $line->next while defined $line->next;
    while (defined $line){
        last if $limit == 0;
        my $copy = $line;
        $line = $line->prev;
        next unless ($copy->get_text(0) =~ /$regex/i);
        $view->remove_line($copy);
        $limit-- if $limit;
    }
    $view->redraw();
}


Irssi::command_bind('crapbuster-levels', \&cmd_crapbuster_levels);
Irssi::command_bind('crapbuster-regex',  \&cmd_crapbuster_regex);
