use strict;
use warnings;
use experimental 'signatures';

our $VERSION = '0.1'; # 02d69b7d9e6ff2e
our %IRSSI = (
    authors     => 'Nei',
    contact     => 'Nei @ anti@conference.jabber.teamidiot.de',
    url         => "http://anti.teamidiot.de/",
    name        => 'mute_inactive',
    description => 'Mute inactive windows by decolouring their texts.',
    license     => 'ISC',
   );
die "This script requires Irssi 1.4 or later"
    if (Irssi::parse_special('$abiversion')||0) < 37;

use Irssi;

my $active_win;
my $active_target;
my $active_tag;

sub set_win {
    my $win = Irssi::active_win;
    $active_win = $win->{_irssi};
    $active_target = $win->{active} ? $win->{active}{name} : '';
    $active_tag = $win->{active_server} ? $win->{active_server}{tag} : '';
    $win;
}

sub init {
    set_win();
    Irssi::command('^foreach window scrollback redraw');
}

Irssi::signal_add +{
    'gui render line text'
	=> sub ($dest, $str, $meta) {
	    $$str = Irssi::format_string_expand('%w') . Irssi::strip_codes($$str)
		unless $dest->{window}{_irssi} == $active_win
		&& (!length $dest->{target} || $dest->{target} eq $active_target)
		&& (!$dest->{server} || $dest->{server}{tag} eq $active_tag);
	},

    'window item changed'
	=> sub {
	    set_win()->command('^scrollback redraw');
	},

    'window changed'
	=> sub ($win, $old) {
	    set_win()->command('^scrollback redraw')
		if $win;
	    $old->command('^scrollback redraw')
		if $old;
	},
};

init();
