error_class = ''
error_message = ''

from xml.sax import handler

# we will use a few global variables
# from the main script
from __main__ import ENC, start_after


class insuma_handler (handler.ContentHandler):
    def __init__(self):
        """These are the attributes of the insuma_handler class:"""
        
        self.total_hits = 0
        self._total_hits_exact = 0
        self.hits = 0
        self.text_buf = ''
        self.level = 0
        self.counter = start_after
        
        
    def set_attributes(self, attrs):
        """This method sets attribute values"""
        
        self.total_hits = int(attrs.get('total_hits', '0'))
        self.hits = int(attrs.get('hits', '0'))
        self.total_hits_exact = int(attrs.get('total_hits_exact', '0'))
        
        
    def startElement(self, name, attrs):
        """ An element starts.
        If it is the RESULT, we just set attributes for later use.
        If it is an ERROR, we store ERROR_CLASS and set LEVEL to -1
        (LEVEL is the attribute, that shows what element we're in).
        If it is DOCUMENT, we print out its number (COUNTER) and URL,
        set LEVEL to 1 and increase the COUNTER.
        If it is a subelement of a DOCUMENT, we print out the name
        and set LEVEL to 2."""
        
        global error_class
        if name == 'result':
            self.set_attributes(attrs)
        elif name == 'error':
            self.level = -1
            error_class = attrs['class']
        elif name == 'document':
            self.level = 1
            print str(self.counter) + '. <a href="' + attrs['url'].encode(ENC) + '">' + attrs['url'].encode(ENC) + '</a><br>'
            self.counter += 1
        elif self.level == 1:
            print '<strong>' + name + ':</strong> '
            self.level = 2
            self.text_buf = ''
    
    def endElement(self, name):
        """ An element ends.
        If it is anything other than ERROR, we decrease LEVEL
        and print line break.
        If it is an ERROR, we raise an exception.
        In this case parsing stops, and error handling starts.
        Error handling is done in the main script,
        using ERROR_CLASS and ERROR_MESSAGE from this module."""
        
        if self.level == 2:
           print self.text_buf 
        if self.level > 0:
           self.level -= 1
           print '<br>'
        elif self.level == -1:
            raise SAXException('Insuma error', None)

    def characters(self, content):
        """ Some text is found.
        If we're in a subelement of a DOCUMENT (i.e.,
        LEVEL equals 2), we add the text to the TEXT_BUF.
        We cannot just print it out, because print operator
        in Python always adds a newline (or a space)
        in the end of line, which may cause errors in
        certain situations.
        If we're inside of an ERROR element, we store
        the text to the ERROR_MESSAGE variable."""
        
        global error_message
        if self.level == 2:
            self.text_buf += content.encode(ENC)
        elif self.level == -1:
            error_message += content

