# -*- coding: utf-8 -*-

"""Statusbot, a GTalk-based (Jabber) status publisher
"""

import re
from cgi import escape
import time, sys, codecs
import jabberbot

__author__ = "Antonio Cavedoni <antonio@cavedoni.org>"
__svnid__ = "$Id$"

def extract_link(input):
    link_r = re.compile(r'(?P<desc>.*?): (?P<uri>(http://.*)+)')
    results = link_r.search(input)
    if results:
        return u'<a href="%s">%s</a>' % \
            (results.group('uri'), escape(results.group('desc')))
    else:
        return escape(input)

def save_status(status):
    """Write status (a unicode string) to filename (as UTF-8)"""
    template = codecs.open('/path/to/template.html', 'r', 'utf-8')
    t = template.read()
    f = codecs.open('/path/to/output.html', 'w', 'utf-8')
    status = extract_link(status)
    f.write(t.replace(u'{{ status }}', status))
    template.close()
    f.close()
    
if __name__ == "__main__":
    statusbot = jabberbot.JabberBot('username', 'password')
    statusbot.connect()
    for x in xrange(10):
        statusbot.check_events()
        status = statusbot.roster.getStatus('jabberid')
        if status:
            save_status(status)
            sys.exit(0)
        time.sleep(0.5)
