from twisted.words.protocols import jabber
from twisted.words.protocols.jabber import client,jid
from twisted.words.xish.domish import Element
from twisted.internet import reactor
import time
import eliza

def authd(xmlstream):
	global thexmlstream
	thexmlstream = xmlstream
	print "we've authd!"
	
	getRoster()
	
	#need to send presence so clients know we're
	#actually online
	presence = Element(('jabber:client','presence'))
	presence.addElement('status').addContent('Online')
	xmlstream.send(presence)
	
	xmlstream.addObserver('/message', gotMessage)
	xmlstream.addObserver('/presence', gotPresence)
	xmlstream.addObserver('/*', gotSomething)


def getRoster():
	# <iq from='juliet@example.com/balcony' type='get' id='roster_1'>
	#   <query xmlns='jabber:iq:roster'/>
	# </iq>
	request = Element((None, 'iq'), attribs={'type': 'get', 'id': 'roster_1'})
	query = request.addElement('query')
	query.attributes['xmlns'] = 'jabber:iq:roster'
	thexmlstream.send(request)
	
def gotMessage(el):
	global thexmlstream, elizaIns
	if el.body is None: return
	try:
		sendComposing(el.attributes['from'], el.attributes['id'])
	except KeyError:
		print "id not found"
		sendComposing(el.attributes['from'], "12345")
	
	print "sleeping . . . ",
	time.sleep(5)
	print "slept"
	sendMessage(el.attributes['from'], elizaIns.respond(str(el.body)))

def sendComposing(to, id):
	#<message to='juliet@example.com/balcony'>
	#<x xmlns='jabber:x:event'>
	#	<composing/>
	#	<id>foo</id>
	#</x></message>
	composing = Element((None,'message'), attribs={'from': 'chimeratest@unstable.nl', 'to': to})
	x = composing.addElement('x')
	x.attributes['xmlns'] = 'jabber:x:event'
	x.addElement('id').addContent(id)
	x.addElement('composing')
	thexmlstream.send(composing)
	
def sendMessage(to, body):
	global myid
	message = Element(('jabber:client','message'), attribs={'to': to, 'type': 'chat'})
	
	message.addElement('body').addContent(body)
	x = message.addElement('x')
	x.attributes['xmlns'] = 'jabber:x:event'
	x.addElement('composing')
	myid+=1
	x.addElement('id').addContent("aaa"+str(myid))
	
	thexmlstream.send(message)
	
def gotSomething(el):
	print 'Got something: %s -> %s' % (el.name, str(el.attributes))
	
def gotPresence(el):
	global thexmlstream
	print 'We got a presence message!'
	print repr(el.attributes)
	try:
		if el.attributes['type'] == 'subscribe':
			# Grant every subscription request
			thexmlstream.send(domish.Element(('jabber:client', 'presence'), 
			attribs={
				'from': el.attributes['to'],
				'to':el.attributes['from'],
				'type':'subscribed'
			}))
			print el.attributes['from'], "added to list"
	except KeyError:
		# Big fat ignore
		pass

global elizaIns, myid
myid = 0
elizaIns = eliza.eliza()

myJid = jid.JID('chimeratest@unstable.nl/twisted')
password = "1234"

factory = client.basicClientFactory(myJid, password)
factory.addBootstrap('//event/stream/authd' ,authd)

reactor.connectTCP('localhost', 5222, factory)
reactor.run()

