#!/usr/bin/env tclsh8.6
#
# xnotify.tcl: show message notifications using xnotify.
#
# To install in the default directory:
#
#	# make install
#
# To install on a different prefix (i.e. your homedir)
#
#	$PREFIX=${HOME} make install
#
# The extension processes PRIVMSG commands, checking if:
#
# - The user is mentioned or
# - The chat the message is from is a private one
# - The application is on focus
#
# If the condition above holds true, a notification popup will appear
# on the screen.
#
# In addition, clicking on the popup will raise IRCTk, switching
# automatically to the channel with the reported message in it.
#
# This extension requires xnotify to be installed to work.
#

source $::env(IRCTK_TCL_SDK)

set name "XNotify"
set version 1.0.0

proc notify {msg} {
	#
	# If the user is actively using the program, there is no
	# need to show the notification.
	#
	if {"[dict get $msg status]" eq "away" || "[dict get $msg focus]" eq true} {
		return
	}

	#
	# Show the popup
	#
	if {"[dict get $msg level]" eq "mention"} {
		puts $::fd [format "CMD:%s,%s\t%s on %s: %s" \
		    [dict get $msg network] [dict get $msg channel] \
		    [dict get $msg nick] \
		    [dict get $msg channel] \
		    [string trimleft [join [dict get $msg args] " "] ":"]]

		flush $::fd
	}
}

#
# This happen when a user clicks on a notification window
#
proc showwindow {fd} {
	if {[gets $fd line] < 0} {
		close $::fd
		set ::fd [open "|xnotify -G NE -s 10 -b 1" r+]

		return
	}

	set msg [split $line ","]

	#
	# Tell IRCTk to come up in foreground.
	#
	::irctk::ircsend [lindex $msg 0] [lindex $msg 1] "RAISE" ""

	#
	# Switch to the channel with the message mentioning us.
	#
	::irctk::ircsend [lindex $msg 0] [lindex $msg 1] "SWITCH" [lindex $msg 1]
}

#
# That's right. The extension runs it's own instance of xnotify as a child.
#
set fd [open "|xnotify -G NE -s 10 -b 1" r+]

#
# Custom events.
#
fileevent $fd readable "showwindow $fd"

::irctk::init $name $version {}

::irctk::filter irc
::irctk::filter privmsg notify

::irctk::loop
