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

# Copyright (c) 2004 - 2005 Detlev Offenbach <detlev@die-offenbachs.de>
#

"""
Module implementing a base class for all of eric3s XML handlers.
"""

import codecs
import sys
from types import UnicodeType

from xml.sax.handler import ContentHandler

class XMLHandlerBase(ContentHandler):
    """
    Class implementing the base class for al of eric3s XML handlers.
    """
    def __init__(self):
        """
        Constructor
        """
        self.startDocumentSpecific = None
        
        self.elements = {
        }
        
        self.buffer = ""
        
        self.encoder = codecs.lookup(sys.getdefaultencoding())[0] # encode,decode,reader,writer
        
    def utf8_to_code(self, text):
        """
        Private method to convert a string to unicode and encode it for XML.
        
        @param text the text to encode (string)
        """
        if type(text) is not UnicodeType:
            text = unicode(text, "utf-8")
        return self.encoder(text)[0] # result,size
        
    def unescape(self, text, attribute=0):
        """
        Private method used to unescape certain characters.
        
        @param text the text to unescape (string)
        @param attribute flag indicating unescaping is done for an attribute
        """
        if attribute:
            return text.replace("&quot;",'"').replace("&gt;",">")\
                       .replace("&lt;","<").replace("&amp;","&")
        else:
            return text.replace("&gt;",">").replace("&lt;","<").replace("&amp;","&")
        
    def startDocument(self):
        """
        Handler called, when the document parsing is started.
        """
        self.buffer = ""
        if self.startDocumentSpecific is not None:
            self.startDocumentSpecific()
        
    def startElement(self, name, attrs):
        """
        Handler called, when a starting tag is found.
        
        @param name name of the tag (string)
        @param attrs list of tag attributes
        """
        try:
            self.elements[name][0](attrs)
        except KeyError:
            pass
            
    def endElement(self, name):
        """
        Handler called, when an ending tag is found.
        
        @param name name of the tag (string)
        """
        try:
            self.elements[name][1]()
        except KeyError:
            pass
            
    def characters(self, chars):
        """
        Handler called for ordinary text.
        
        @param chars the scanned text (string)
        """
        self.buffer += chars
        
    def defaultStartElement(self, attrs):
        """
        Handler method for common start tags.
        
        @param attrs list of tag attributes
        """
        self.buffer = ""
        
    def defaultEndElement(self):
        """
        Handler method for the common end tags.
        """
        pass
