use strict;
use vars qw($VERSION %IRSSI);

use Irssi;
use Irssi::TextUI;

$VERSION="0.0.5";
%IRSSI=(
	authors		=> 'janus',
	contact		=> 'janus@errornet.de',
	name		=> 'law&order',
	description	=> 'Remembers persons saying keywords on a channel, bind keys for act on them',
	license		=> 'GPL v2',
	url		=> 'http://janus.errornet.de/scripts.x?f=law_order.pl',
);

#
# Add to statusbar:
# /statusbar window add -alignment right law_order_bar
#
# Set kick-key
# /bind meta-x /law_order_kick
#
# Alert-Message in active Window
# /set alert_in_active 1
#
# Turn off statusbar
# /set show_law_order_bar 0
#



my($last)={};
my(@chans)=qw(#area319 #linuxger #bsd.de #lang.c #test.a319);
my($match_all_chans)='|(arschloch|sau)';
my($kick_reason)="PISS OFF!";
my($regex)={
	'#area319'	=> '\U(wixer|test)\E'.$match_all_chans,
	'#linuxger'	=> 'idiot|depp|test'.$match_all_chans,
	'#bsd.de'	=> 'wixer|test'.$match_all_chans,
	'#test.a319'	=> 'wixer|test'.$match_all_chans,
};
my($status_bar_text)="ALERT: none";
my($show_law_order_bar)=(1);

sub cmd_law_order_kick {
	my($data,$s,$wi)=@_;
	return if(!$s->{connected});
	$s->command("KICK $last->{chan} $last->{nick} $kick_reason");
}

sub check_law_order {
	my($s,$data)=@_;
	my($channel,$nick)=split(/ +/,$data);
	if($last->{nick} eq $nick&&$last->{chan} eq $channel) {
		$status_bar_text="ALERT: none";
		Irssi::statusbar_items_redraw('law_order_bar') if(Irssi::settings_get_int('show_law_order_bar'));
	}
}

sub dirt_scan {
	my($s,$data,$nick,$host)=@_;
	my($target,$text)=split(/ :/,$data,2);
	return if($target eq $nick);
	return if(!$regex->{$target});
	if($text=~m/$regex->{$target}/) {
		$last->{nick}=$nick;
		$last->{word}=$text;
		$last->{host}=$host;
		$last->{chan}=$target;
		if(Irssi::settings_get_int('alert_in_active')) {
			my($win)=Irssi::windows;
			my($active)=$win->{active};
			$win->print("%RALERT%n: %W$last->{chan}%n: %Y$last->{nick}%n",MSGLEVEL_SNOTES);
		}
		Irssi::statusbar_items_redraw('law_order_bar') if(Irssi::settings_get_int('show_law_order_bar'));
	}
}

sub law_order_bar {
	my($i,$s)=@_;
	#$status_bar_text="%RALERT%n: %W$last->{chan}%n: %Y$last->{nick}%n";
	$status_bar_text="ALERT: ".($last->{chan}||"none").($last->{nick}?": $last->{nick}":"");
	$i->default_handler($s,undef,$status_bar_text,1);
}

Irssi::statusbar_item_register('law_order_bar','{sb $0-}','law_order_bar');
Irssi::statusbars_recreate_items();

Irssi::settings_add_int('misc','show_law_order_bar',$show_law_order_bar);
Irssi::settings_add_int('misc','alert_in_active',1);


Irssi::signal_add('event privmsg','dirt_scan');
Irssi::signal_add('event kick','check_law_order');

Irssi::command_bind('law_order_kick','cmd_law_order_kick');

