########################################################################
# amara/writers/htmlwriter.py
"""
HTML writer for XSLT processor output
"""

from amara.namespaces import XML_NAMESPACE, XMLNS_NAMESPACE
from amara.writers.xmlwriter import xmlwriter
from amara.writers._htmlprinters import htmlprinter, htmlprettyprinter

class htmlwriter(xmlwriter):
    """
    Takes events such as those generated by an XSLT processor and
    invokes a serializer to produce HTML. Uses XML syntax for
    elements in a non-empty namespace. Instructs the serializer to
    insert a Content-Type 'meta' element in the first 'head' element.
    """

    def _complete_head_element(self, _base_class=xmlwriter):
        # `xmlwriter` clears `self._element_name` before returning
        if self._element_name and self._element_namespace is None:
            head_tag = (self._element_name.lower() == u'head')
        else:
            head_tag = False

        _base_class._complete_element(self)

        if head_tag:
            # Output the META tag
            attrs = ((u'http-equiv', u'Content-Type'),
                     (u'content', (self.output_parameters.media_type +
                                   u'; charset=' +
                                   self.output_parameters.encoding)),
                     )
            self._printer.start_element(None, u'meta', (), attrs)
            self._printer.end_element(None, u'meta')
            # restore "normal" completion function
            assert self._complete_element.im_self is self
            del self._complete_element
        return

    def start_document(self):
        params = self.output_parameters
        params.setdefault('media_type', 'text/html')
        version = params.setdefault('version', '4.0').encode('ascii')
        encoding = params.setdefault('encoding', 'iso-8859-1').encode('ascii')
        indent = params.setdefault('indent', True)
        if indent:
            printer_class = htmlprettyprinter
        else:
            printer_class = htmlprinter

        self._printer = printer_class(self.stream, encoding)
        self._printer.start_document(version)
        self._complete_element = self._complete_head_element

        self._namespaces = [{None: None,
                             'xml': XML_NAMESPACE,
                             'xmlns': XMLNS_NAMESPACE}]
        self._attributes = {}
        return


from amara.writers import _userwriter

class _htmluserwriter(_userwriter, htmlwriter):
    def __init__(self, oparams, stream):
        htmlwriter.__init__(self, oparams, stream)

