from Products.PortalTransforms.interfaces import itransform
try:
    # use Zope's rest writer by default
    from reStructuredText import HTML
    USE_ZOPE=1
except ImportError:
    from Products.PortalTransforms.libtransforms.html4zope import Writer
    from docutils.core import publish_string
    USE_ZOPE=0

import sys
if sys.version_info < (2,2):
    # XXX: fix the types module to make it docutils working with py2.1
    import types
    types.StringTypes = (types.UnicodeType, types.StringType)

class warnings:
    def __init__(self):
        self.messages = []

    def write(self, message):
        self.messages.append(message)

def reSTwriter(orig):
    """uses either the zope implementation of reST or the PortalTransforms html4zope
    """
    settings = {'report_level': 1,
                'halt_level': 6,
                'warning_stream': warnings(),
                'documentclass': '',
                'traceback': 1,
               }

    if USE_ZOPE:
        return HTML(orig, report_level = settings['report_level'])
    else:
        return publish_string(writer=Writer(), source=orig, settings_overrides=settings)

class rest:
    __implements__ = itransform

    __name__ = "rest_to_html"
    inputs  = ("text/x-rst", "text/restructured",)
    output = "text/html"

    def name(self):
        return self.__name__

    def convert(self, orig, data, **kwargs):
        # do the format
        html = reSTwriter(orig)
        #warnings = ''.join(pub.settings.warning_stream.messages) #XXX what todo with this?
        html = html.replace(' class="document"', '', 1)
        data.setData(html)
        return data

def register():
    return rest()
