# iChat timestamps. Plugin to add iChat-style timestamps to xchat.
# Copyright 2004 Sam Morris
#
# This plugin is distributed under the terms of the GNU General Public License. *
# Version 0.2!
#
# BUG: sent actions (/me) do not cause the timestamp for a channel to be
#      updated.
# BUG: notices (and privmsgs) sometimes cause the timestamp for the channel
#      you are in when you recieve them to be reset. This is because when they
#      are recevied, the context for the new window has not yet been created.
# BUG: onClose crashes xchat!!

__module_name__ = "ichat-timestamps" 
__module_version__ = "0.2" 
__module_description__ = "Prints iChat-style timestamps."

import xchat
import time

def onClose():
	contextkey = context_to_key(xchat.get_context())
	if contextkey in times:
		del times[contextkey] # crashes xchat!

def onSince(word, word_eol, userdata):
	if (len(word) == 1):
		channel = xchat.get_info("channel");
	else:
		channel = word[1]
	
	contextkey = context_to_key(xchat.find_context(None, channel))
	try:
		xchat.prnt("%s: silent for %d seconds." % (channel, time.time()-times[contextkey]))
	except KeyError:
		xchat.prnt("%s: silent since the big bang." % (channel))

def onTslist(word, word_eol, userdata):
	for contextkey in times.keys():
		xchat.prnt("%s: silent for %d seconds" % (contextkey, times[contextkey]))
	
	xchat.prnt("End of list.") #why does xchat say "no such command?"

def context_to_key(context):
	#This will have to pass as a unique ID for contexts.
	# for some reason this only appears to return the network name--however the plugin
	# seems to work fine... most perplexing!
	return "%s:%s" % (context.get_info("network"), context.get_info("channel"))

def updateTime(word, word_eol, userdata):
	contextkey = context_to_key(xchat.get_context())

	now = time.time();
	last = times.get(contextkey, 0)

	if (now - last > timeout):
		xchat.prnt("\n%s\t\n" % (time.strftime("%H:%M", time.localtime(now))))

	times[contextkey] = now

#xchat.hook_print("Close Context", onClose) #crashes xchat! eep!

xchat.hook_command("since",   onSince,   help="Prints the time elapsed since the last activity in the current, or specified, window.")
xchat.hook_command("tslist",  onTslist,  help="Lists windows and idle times.")

xchat.hook_command("",       updateTime) # trap all commands
xchat.hook_server("PRIVMSG", updateTime)
xchat.hook_server("ACTION",  updateTime)

times = {}
timeout = 5 * 60

xchat.prnt("iChat timestamps loaded.")
