use Irssi;
use strict;
use vars qw($VERSION %IRSSI);
$VERSION = '0.0.1';
%IRSSI = (
        authors     => 'Sebastian Groeneveld',
        contact     => 'dracuul78@hotmail.com',
        name        => 'query_verbose',
        description => 'displays server events related to a query window in that window',
        license     => 'GPLv2',
        url         => 'undefined',
        changed     => '24/03/2005'
);

sub report_to_query {
    my ($server, $nick, $msg, $lvl) = @_;
    my $win = $server->window_item_find($nick); 
    
    if ($win && ($win->{type} eq "QUERY")) {
        $win->print($msg, $lvl);
    }
}

sub sig_join {
    my ($server,$channel,$nick,$address) = @_;    
    my $msg = Irssi::settings_get_str('query_msg_join');
    if (length($msg) <= 1) {
        return;
    }
    $msg =~ s/\$n/$nick/g;
    $msg =~ s/\$a/$address/g;
    report_to_query($server, $nick, $msg, MSGLEVEL_JOINS);
}

sub sig_quit {
    my ($server,$nick,$address, $reason) = @_;
    my $msg = Irssi::settings_get_str('query_msg_quit');
    if (length($msg) <= 1) {
        return;
    }
    $msg =~ s/\$n/$nick/g;
    $msg =~ s/\$a/$address/g;
    $msg =~ s/\$r/$reason/g;
    report_to_query($server, $nick, $msg, MSGLEVEL_QUITS);
}

sub sig_mode {
    my ($channel, $nick, $setby, $mode, $type) = @_;
    my $msg;

    my $realnick = $nick->{'nick'};

    # +voice  @op
    
    if ($mode eq "+") {
        if ($type eq "+") {
            $msg = Irssi::settings_get_str('query_msg_mode_voice');
        } elsif ($type eq "-") {
            $msg = Irssi::settings_get_str('query_msg_mode_normal');
        }
    }
    if (length($msg) <= 1) {
        return;
    }
                    
    $msg =~ s/\$n/$realnick/g;
    report_to_query($channel->{'server'}, $realnick, $msg, MSGLEVEL_MODES);
}


Irssi::signal_add_first('message join', \&sig_join);
Irssi::signal_add_first('message quit', \&sig_quit);
Irssi::signal_add_first('nick mode changed', \&sig_mode);

Irssi::settings_add_str('query_verbose', 'query_msg_join', '%g$n%n %K[%n$a%K]%n has come online');
Irssi::settings_add_str('query_verbose', 'query_msg_quit', '%K$n%n %K[%n$a%K]%n has quit %K[%n$r%K]%n');
Irssi::settings_add_str('query_verbose', 'query_msg_mode_normal', '%y$n%n has gone away');
Irssi::settings_add_str('query_verbose', 'query_msg_mode_voice', '%g$n%n has returned');