# -*- coding: UTF-8 -*-
"""
This macro is dedicated to reproduce a bug in 1.6/MoinMoin/parser/text_xslt.py.

This implementation base on the 1.6/MoinMoin/macro/Include.py but reduced to the
essential code to be able to reproduce the bug.
"""

import StringIO
from MoinMoin import wikiutil
from MoinMoin.Page import Page

_sysmsg = '<p><strong class="%s">%s</strong></p>'

rawcontent = u"""<?xml version="1.0" encoding="UTF-8"?>
<Product xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="IVM" version="2.00" manufacturer="SIEMENS">
<!-- Sammelanschlußkennzahl -->
<!-- Bündel-Kennzahl -->
<!-- Automatisches Auflegen für Info- Mailbox -->
<!-- max. Mailbox- Länge -->
<!-- max. Länge einer ankommenden Nachricht in Sekunden -->
<!-- min. Länge einer ankommenden Nachricht in Sekunden -->
<!-- Länge des Mailbox- Passworts -->
<!-- Flag Gebührenmissbrauch verhindern -->
<!-- Automatisches Löschen von Nachrichten die Älter sind als angegeben (in Tagen) -->
</Product>"""

def execute(macro, text):
    """
    This function match the Include macro in main parts.

    #ror = RedirectOutputRequest(macro.request)
    #ror.start(sent_headers=True)
    #try:
    #    cid = macro.request.makeUniqueID("Include_%s" % wikiutil.quoteWikinameURL(inc_page.page_name))
    #    inc_page.send_page(ror, content_only=1, content_id=cid, omit_footnotes=True)
    #    result.append(ror.getoutput())
    #except UnicodeDecodeError, e:
    #    result.append(_sysmsg % ('error', _('Encoding %s error: %s' % (attach_encoding, e,))))
    """
    result = []
    request = macro.request
    _ = request.getText
    fmt = macro.formatter.__class__(request)
    fmt._base_depth = macro.formatter._base_depth
    inc_page = Page(request, macro.formatter.page.page_name + 'utf8bug', formatter=fmt)
    inc_page.set_body(rawcontent)

    # output the included page
    strfile = StringIO.StringIO()
    request.redirect(strfile)
    try:
        cid = request.makeUniqueID("Include_%s" % wikiutil.quoteWikinameURL(inc_page.page_name))
        inc_page.send_page(content_only=1, content_id=cid,
                           omit_footnotes=True)
        result.append(strfile.getvalue())
    except UnicodeDecodeError, e:
        result.append(_sysmsg % ('error', _('Encoding error:') + e.__str__()))
    
    request.redirect()
    
    return ''.join(result)
