#!/uns/bin/python

from Tkinter import *
from ScrolledText import *
import os, sys, regex, string, re

def get_env(envvar, default=''):
	# This should also work
	# return os.environ.get(envvar, default)
	try:
		return os.environ[envvar]
	except:
		return default
	
class MiniPuff(Frame):
	def __init__(self, master=None):
		Frame.__init__(self)
		self.pack(expand=1, fill=BOTH)
		self._create_widgets()
		self._populate()

	def _create_widgets(self):
		self._text = ScrolledText(self, height=8)
		self._text.pack(side=TOP, expand=1, fill=BOTH)

		self._close = Button(self, text="Close", command=self.quit)
		self._close.pack(side=BOTTOM, expand=0, fill=X)

	def _populate(self):
		if recipient == my_id:
			self._text['background'] = 'black'
			self._text['foreground'] = 'white'

		# Color-code the header by sender
		self._text.insert('end', "[%s] by %s\n\n" % (category, sender))
		self._text.insert('end', pufftext)
		normal_sig = "\n-- <%s> for %s at %s --" % (sign, recipient, date)
		self._text.insert('end', normal_sig)

if __name__ == '__main__':
	#--------------------------------------------------
	# Catch all the message headers in the envvars
	#--------------------------------------------------
	# Sender: real name of person sending puff
	sender = get_env('GALE_TEXT_MESSAGE_SENDER', 'Unknown sender')
	# Category, eg "pub/comp/linux"
	category = get_env('GALE_CATEGORY', 'Unknown category')
	# Sign: Gale ID of sender, eg "nobody@ofb.net"
	sign = get_env('GALE_SIGNED', 'Unknown sig')
	# Date message was sent, eg "1998-08-24 15:18:47"
	date = get_env('GALE_TIME_ID_TIME', '1998-sometime')[5:]
	# Recipient, plain text, eg "Tessa Lau"
	recipient = get_env('GALE_TEXT_MESSAGE_RECIPIENT', '*everyone*')
	# Who the puff is addressed to, eg "Tessa Lau"
	my_id = get_env('GALE_FROM', 'Me')
	# Status of recipient for a receipt, eg "in/present"
	status = get_env('GALE_TEXT_NOTICE_PRESENCE', 'Unknown status')
	# Client used to send puff
	idclass = get_env('GALE_TEXT_ID_CLASS', 'Unknown client')

	# Get the text of the message
	pufftext = sys.stdin.read()

	# Filter out pings
	cats = string.split(category, ':')
	if '/ping' in cats:
		sys.exit(0)

	# Receipts
	if regex.search('/receipt', category) != -1:
		s = '* %s received: %s <%s> (%s) via %s' %\
			(date, status, sign, sender, idclass)
		# print s
		sys.exit(0)

	p = os.fork()
	if p == 0:
		a = MiniPuff()
		a.mainloop()
	else:	# parent
		sys.exit(0)
