# -*- coding: utf-8 -*-
# Hah, don't you love the pervasiveness of Emacs?
from xml.sax.handler import ContentHandler
from xml.sax import make_parser
from buddies import Logic
import re
import globalv

class MurrayHandler(ContentHandler):
    """
    FIXME()
    """
    cl = buddies.Logic()
		
    def __init__(self):
        self.__ElementStack = []
        self.__currentCharacters = {}
        
    def startElement(self, name):
        """Blablabla"""
        try:
            getattr(self, "__handle" + name.lower() + "Start")(attrs)
        except AttributeError:
            pass
        

    def endElement(self, name):
        """FIXME()"""
        try:
            getattr(self, "__handle" + name.lower() + "End")(attrs)
        except AttributeError:
            pass    
            
    def characters(self, characters):
        """reads characters"""
        if self.__record:
            self.__currentCharacters[self.__ElementStack[-1]] += characters
    
    def __handlepresenceStart(self, attrs):
        """FIXME"""
        self.__ElementStack.append('presence')
        self.__type = attrs['type'] if attrs.has_key('type') else None
        sender = attrs['from'] if attrs.has_key('from') else None
        if sender:
            bacon = self.__getUID(sender)
        else:
            raise RuntimeError
        self.__uid = bacon[0]
        self.__alias = bacon[1]
        self.__olStatus = 'online'
        self.__olMessage = ''
                
    def __handlepresenceEnd(self):
        """FIXME"""
        if self.__ElementStack.pop() == 'presence':
            if self.__type == 'unavailable':
                cl.setOnlineStatus(self.__uid, self.__alias, 0, '')
            elif self.__type == 'subscribe':    
                """FIXME: subscribe"""
                #Simply pass the message on to our client
                pass
            elif self.__type == 'unsubscribe':
                """If an unsubscribe-request comes, remove the requesting user from the roster"""
                cl.remove(self.__uid)
                pass
            else:
                cl.receiveOnlineStatus(self.__uid, self.__alias, 
                                    self.__olStatus, self.__olMessage)
            self.__currentElement = False
            self.__presence = False
            self.__type = False
            self.__from = False
        else:
            raise RuntimeError
            
    def __handleshowStart(self, attrs):
        """FIXME"""
        if self.__ElementStack[-1] == 'presence':
            self.__ElementStack.append('show')
            self.__record = True
        else:
            raise RuntimeError
        
    def __handleshowEnd(self):
        """FIXME"""
        if self.__ElementStack.pop() == 'show':
            self.__record = False
            if self.__currentCharacters['show'] in ('away', 'chat', 'dnd', 'xa'):
                self.__olStatus = self.__currentCharacters['show']
        else:
            raise RuntimeError
        
    def __handlestatusStart(self, attrs):
        """FIXME"""
        if self.__ElementStack[-1] == 'presence':
            self.__ElementStack.append('status')
            self.__record = True
        else:
            raise RuntimeError
        
    def __handlestatusEnd(self):
        """FIXME"""
        if self.__ElementStack.pop() == 'status':
            self.record = False
            if self.__currentCharacters['status']:
                self.__olMessage = self.__currentCharacters['status']
            
    def __getUid(self, sender):
        """gets uid and alias out ouf the jib.
        
        returns a (uid, alias) tuple"""
        rex = re.compile('@(.*)/')
        bacon = re.split(rex, sender)
        alias = bacon[0]
        uid = bacon[1].split('.')[0]
        return (uid, alias)
    
    

def handle_incoming(message):
	"""handles incoming XMPP-Messages"""
	parser = make_parser()
	parser.setContentHandler(IncomingXMPPHandler)
	parser.feed(message)
	parser.close()
	globalv.XMPPSERVER.requestSend(message)