use strict;
use warnings;
use Xchat qw(:all);
use POSIX qw(strftime);
use File::Spec ();
use POSIX qw(:sys_wait_h);

my $viewer = "gedit";
register(
	"Viewlog",
	"1.0.0",
	"Open the log for the current context in the configured viewer",
);

my %children;
# Child Reaper
hook_timer( 1_000, sub {
	for my $pid ( keys %children ) {
#		prnt "Reaping $pid";
		my $exit = waitpid( $pid, WNOHANG );

		if( $exit == -1 or $exit > 0 ) {
#			prnt "Reaped $pid";
			delete $children{ $pid };
		}
	}

	return KEEP;
});
hook_command( "VIEWLOG", sub {
	my $server = to_lower( get_info( "server" ) || "server" );
	my $channel = to_lower( get_info "channel" );
	my $network = get_info( "network" ) || "NETWORK";

	my $logmask = get_prefs "irc_logmask";

	for( $logmask ) {
		s/%s/$server/g;
		s/%c/$channel/g;
		s/%n/$network/g;
	}

	my $filename = strftime( $logmask, localtime );
	$filename = File::Spec->rel2abs( $filename,
		File::Spec->catdir( get_info( "xchatdirfs" ), "xchatlogs" )
	);

	if( -f $filename ) {
		display_file( $filename );
	} else {
		command( qq{GUI MSGBOX "Log file for the current channel/dialog does not seem to exist. ($filename)"} );
	}

	return EAT_XCHAT;
});

sub to_lower {
	if( !nickcmp( '{', '[' ) ) {
		return rfc_lc( shift );
	} else {
		return lc shift;
	}
}

sub rfc_lc {
	my $str = shift;
	$str =~ tr/[]\\/{}|/;
	return lc $str;
}

sub display_file {
	my $filename = shift;

	my $pid = fork;
	if( defined $pid && $pid == 0 ) {
		fork && exit;
		unless( exec( $viewer, $filename ) ) {
			warn "Failed to start log viewer '$viewer': $!";
			exit(1);
		}
	} elsif( defined $pid ) {
#		prnt "PID = $pid";
		$children{ $pid } = 1;
	} else {
		warn "Failed to fork: $!";
	}
}
