package channels;
#: Version: 0.2
#: Description: Separates out regex-matching lines into a new window
#: Author: Jakykong

# I, the author, hereby release this file into the public domain. Hack away.

BEGIN {
	$::world->requireplugin('KCWin');
}

#Gag everything, but we'll echonl things that don't match.
$::world->trigger('.*','/channels::check($_[0], "$colorline")', {gag => 1, keepexecuting => 1} );


sub help {
	$::world->echonl(<<"EOHELP");
Channels is a simple plugin to yank lines out of the world window
and put then in other windows. It's most obvious use is chat channels,
which usually have something like "[NAME]" at the beginning.

Once the plugin is loaded, there is only one function to call:
/channels::new("name","regex");

where "name" is the name that should appear in the title bar of the
new window, and "regex" is the pattern to match for text.

Use /channels::list() for a list of currently defined channels. To
remove a channel, use /channel::del(num), where num is the number of
the channel.

Enjoy!
EOHELP
}




#Holds the channels and associated windows.
my %chans = ();
my %windowlist = ();
my $bank = 0;

sub check {
	#Check for matches. Echo to the respective window.
	my ($line, $colorline) = @_;

	my $result = 0;
	foreach $k ( keys %chans ) {
		if ( "$line" =~ m/$k/ ) {
			$result = 1;
			$chans{"$k"}->feed("$colorline");
		}
	}

	unless ( $result ) {
		$::world->echo("$colorline");
	}
}


sub del {
	#Deletes a channel, by the number given.
	my $number = $_[0];
	foreach $k ( keys %chans ) {
		if ( "$k" eq $windowlist->{$number}[1] ) {
			$chans{$k}->destroy();
			delete $chans{$k};
			delete $windowlist{$k};
		}
	}
}


sub new {
	#Creates a new channel.
	my ($name, $regex) = @_;

	$chans{$regex} = new_window($name);
	$bank = $bank + 1;
	$windowlist->{$bank} = [$bank,$regex,$name];
	$::world->echonl( ::colorize("&rCreated channel #$bank, $name.") );
}

sub list {
	#Lists all open windows
	foreach $i ( keys %windowlist ) {
		$k = @windowlist->{$i}[2];
		$world::->echonl( "#$i: $k" );
	}
}

sub new_window {
	#Returns a new KCWindow without displaying the clear button.
	#Syntax: new_window(name,func) where func is optional.
	my $n = $_[0];
	my $window = KCWin->new;

	#Pass a function to new_window to have it run on close.
	#Default behavior is to simply hide the window,
	#so you can show it later via $window->show().
	if ( @_ > 1 ) {
		my $func = $_[1];
	}
	else {
		my $func = sub{ $window->hide(); };
	}

	$window->set_title("$n");
	$window->signal_connect(delete_event => sub {
				&func();
				return 1;
				});
	$window->{BTNCLEAR}->hide;

	$window->{VBOX}->show_all;
	$window->{BTNCLEAR}->hide;
	$window->show;

	return $window;
}

sub UNLOAD {
	#Destroys any remaining channel windows.
	foreach $k ( keys %chans ) {
		$chans{"$k"}->destroy;
	}
}
