from __future__ import generators

# import Twisted and install

from twisted.internet.threadedselectreactor import install
install()
from twisted.words.protocols.jabber import client, jid#
from twisted.words.xish import domish#
from twisted.internet import reactor

import pygame
from pygame.locals import *

try:
    import pygame.fastevent as eventmodule
except ImportError:
    import pygame.event as eventmodule


# You can customize this if you use your
# own events, but you must OBEY:
#
#   USEREVENT <= TWISTEDEVENT < NUMEVENTS
#
TWISTEDEVENT = USEREVENT

def postTwistedEvent(func):
    # if not using pygame.fastevent, this can explode if the queue
    # fills up.. so that's bad.  Use pygame.fastevent, in pygame CVS
    # as of 2005-04-18.
    eventmodule.post(eventmodule.Event(TWISTEDEVENT, iterateTwisted=func))

def helloWorld():
    print "hello, world"
    reactor.callLater(1, helloWorld)
reactor.callLater(1, helloWorld)

def twoSecondsPassed():
    print "two seconds passed"
reactor.callLater(2, twoSecondsPassed)

def eventIterator():
    while True:
        yield eventmodule.wait()
        while True:
            event = eventmodule.poll()
            if event.type == NOEVENT:
                break
            else:
                yield event
                
def authd(xmlstream):#
    print "authenticated"#

    presence = domish.Element(('jabber:client','presence'))#
    xmlstream.send(presence)#
    
    xmlstream.addObserver('/message',  debug)#
    xmlstream.addObserver('/presence', debug)#
    xmlstream.addObserver('/iq',       debug)   #

def debug(elem):#
    try: print elem.toXml().encode('utf-8').split('<body>')[1].split('</body>')[0]#
    except: print elem.toXml().encode('utf-8')
    print "="*20#
    
myJid = jid.JID('d@jabber.org/twisted_words')#
factory = client.basicClientFactory(myJid, 'd')#
factory.addBootstrap('//event/stream/authd',authd)#
reactor.connectTCP('jabber.org',5222,factory)#
#reactor.run()

def __main__():
    pygame.init()
    if hasattr(eventmodule, 'init'):
        eventmodule.init()
    screen = pygame.display.set_mode((300, 300))
    screen.blit(pygame.image.load('sce.png'),(0,0))

    # send an event when twisted wants attention
    reactor.interleave(postTwistedEvent)
    # make shouldQuit a True value when it's safe to quit
    # by appending a value to it.  This ensures that
    # Twisted gets to shut down properly.
    shouldQuit = []
    reactor.addSystemEventTrigger('after', 'shutdown', shouldQuit.append, True)

    for event in eventIterator():
        if event.type == TWISTEDEVENT:
            event.iterateTwisted()
            if shouldQuit:
                break
        elif event.type == QUIT:
            reactor.stop()
        elif event.type == KEYDOWN and event.key == K_ESCAPE:
            reactor.stop()
                
    pygame.quit()

if __name__ == '__main__':
    __main__()
