from xml.sax import saxutils

from rldjango.common import transform


class RmlFormatter:
    """Writes out parsed XHTML as RML.  some style names
    can be passed in within the constructor."""
    def __init__(self, paraStyle=None):
        self._data = []
        # note this attribute refers to different objects at different times
        self._ptr = self._data
        self.paraStyle = paraStyle or 'normal'

    def content(self, content):
        self._ptr.append(saxutils.escape(content))

    def startHeading(self, level=1):
        #self._ptr.append('<h%d>' % level)
        self._ptr.append('<para style="h%d">' % level)

    def endHeading(self, level=1):
        #self._ptr.append('</h%d>' % level)
        self._ptr.append('</para>')

    def startPara(self, style=None):
        if style is None:
            style = self.paraStyle
        self._ptr = []
        self._ptr.append('<para style=%s>' % saxutils.quoteattr(style))

    def endPara(self):
        paraData = transform.normalizeWhitespace("".join(self._ptr))
        self._ptr = self._data
        self._ptr.append(paraData)
        self._ptr.append('</para>')

    def startUl(self):
        #self._ptr.append('<para>')
        pass

    def endUl(self):
        #self._ptr.append('</para>')
        pass

    def startOl(self):
        #self._ptr.append('<para>')
        pass

    def endOl(self):
        #self._ptr.append('</para>')
        pass

    def startLi(self, style=None):
        if style is None:
            style=self.paraStyle
        self._ptr.append('<para style=%s><bullet>&bull;</bullet>' % saxutils.quoteattr(style))

    def endLi(self):
        self._ptr.append('</para>')

    def startAddress(self):
        self._ptr.append('<para>')

    def endAddress(self):
        self._ptr.append('</para>')

    def startSpan(self):
        pass #RML doesn't do span

    def endSpan(self):
        pass

    def startBold(self):
        self._ptr.append('<b>')

    def endBold(self):
        self._ptr.append('</b>')

    def startItalic(self):
        self._ptr.append('<i>')

    def endItalic(self):
        self._ptr.append('</i>')

    def flowingContent(self, text):
        self._ptr.append(saxutils.escape(text))

    def startLink(self, href):
        self._ptr.append(saxutils.escape(href))

    def endLink(self):
        pass

    def doBr(self):
        self._ptr.append('<br/>')

    def getOutput(self):
        r = '\n'.join(self._ptr)
        self.close()
        return r

    def close(self):
        self._ptr = self._data = None
