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

$VERSION = "0.1";
%IRSSI = (
    authors     => 'Simon Shine',
    contact     => 'simon@shine.eu.org',
    name        => 'nickcompletion_simon',
    description => 'Enable /set completion_format that overrides completion_char and enables %n',
    license     => 'Public domain',
);

Irssi::signal_add_first 'complete word' => \&sig_complete;
Irssi::settings_add_str 'completion', 'completion_extended', '[  %n  ]:';
Irssi::settings_add_str 'completion', 'completion_extended_channels', '#irssi';

sub sig_complete {
    my ($complist, $window, $word, $linestart, $want_space) = @_;

    # only if something has been typed and it's the first word on the line.
    return if ($linestart ne "" or $word eq "" or
        index(Irssi::settings_get_str("cmdchars"), substr($word, 0, 1)) != -1);

    # only if this is a channel.
    return if (!$window->{active} || $window->{active}->{type} ne "CHANNEL");

    my $channels = Irssi::settings_get_str('completion_extended_channels');
    $channels =~ s/^[\s,]+//;
    $channels =~ s/[\s,]+$//;

    my %validchans;
    $validchans{$_} = 1 for (split /[\s,]+/, $channels);

    # only in valid channels, if any are specified
    return if (scalar(keys %validchans) && !$validchans{$window->{active}->{name}});

    my $completion_strict = Irssi::settings_get_bool("completion_strict");
    my $completion_extended = Irssi::settings_get_str("completion_extended");
    for ($window->{active}->nicks()) {
        my $pattern = my $nick = $_->{nick};
        if ($completion_strict) {
            $pattern =~ s/[^a-z]//ig;
            $pattern = $nick if (!length $pattern);
        }
        next unless (index(lc $pattern, lc $word) == 0);
        my $fnick = $completion_extended;
        $fnick =~ s/\%n/$nick/g;
        push @$complist, $fnick;
    }
    Irssi::signal_stop();
    return;
}
