from rldjango.common import transform

from xml.sax import saxutils


class HtmlFormatter:

    def __init__(self, applyStyles=True):
        self._data = []
        # note this attribute refers to different objects at different times
        self._ptr = self._data
        self.applyStyles = applyStyles

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

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

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

    def startPara(self, style='normal'):
        self._ptr = []
        if self.applyStyles:
            self._ptr.append('<p style=%s>' % saxutils.quoteattr(style))
        else:
            self._ptr.append('<p>')

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

    def startUl(self):
        self._ptr.append('<ul>')

    def endUl(self):
        self._ptr.append('</ul>')

    def startOl(self):
        self._ptr.append('<ol>')

    def endOl(self):
        self._ptr.append('</ol>')

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

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

    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 startLi(self):
        self._ptr.append('<li>')

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

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

    def startLink(self, href):
        self._ptr.append('<a href=%s>' % saxutils.quoteattr(href))

    def endLink(self):
        self._ptr.append('</a>')

    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
