from Products.PortalTransforms.interfaces import itransform

try:
    # use Zope's rest writer by default
    from reStructuredText import HTML, render
    USE_ZOPE=1
except ImportError:
    from Products.PortalTransforms.libtransforms.zope27rest import HTML, render
    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)

def reSTwriter(orig, input_encoding, output_encoding, language, warnings=None):
    """uses either the zope implementation of reST or the PortalTransforms html4zope
    """
    settings = {'documentclass': '',
                'traceback': 1,
               }

    warnings = None
    return HTML(orig, input_encoding=input_encoding, output_encoding=output_encoding,
                language_code=language, initial_header_level=2, warnings = warnings,
                settings = 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
        encoding        = kwargs.get('encoding', 'utf-8')
        input_encoding  = kwargs.get('input_encoding', encoding)
        output_encoding = kwargs.get('output_encoding', encoding)
        language        = kwargs.get('language', 'en') 
        html = reSTwriter(orig, input_encoding, output_encoding, language)
        html = html.replace(' class="document"', '', 1)
        data.setData(html)
        return data

def register():
    return rest()
