# -*- coding: utf-8 -*-

"""
Module with various Monkey-Patches which makes MoinMoin generate HTML4 code
which validates with the `W3C validator`_.

.. _W3C validator: http://validator.w3.org
"""

from mmpp import hook



from MoinMoin import request as moinrequest
import re

reStripBadIdChars = re.compile(r"""[^a-zA-Z0-9_]""").sub
RequestBase_makeUniqueID = moinrequest.RequestBase.makeUniqueID

def RequestBase_makeUniqueID__HACK__(self, base):
    return reStripBadIdChars("_", RequestBase_makeUniqueID(self, base))


@hook
def patch_requestMakeUniqueID():
    """
    Monkey-Patch which fixes unique-id generation in the MoinMoin request
    base class, used during content generation. When using the Include()
    macro the method generates ids with slashes in it, which are reported
    as errors by the W3C validator. This will fix errors, but it is an
    Ugly Hack(tm).
    """
    moinrequest.RequestBase.makeUniqueID = RequestBase_makeUniqueID__HACK__



@hook
def patch_lineAnchors():
    """
    Monkey-Patch which disabled generation of "line-#" identifiers for
    HTML elements, thus avoiding validation errors. This is *GLOBALLY*
    disabled, but I hope there is no problem because our theme does not
    use line anchors for styling. Also, this should make MoinMoin a bit
    faster.
    """
    from MoinMoin.formatter import text_html
    text_html.line_anchors = False



from MoinMoin.parser import rst

class HackedRstTranslatorList(list):
    reSubColTag = re.compile(r"""<col(\s+[^>]*)/>""").sub

    def append(self, element):
        if isinstance(element, (str, unicode)):
            element = self.reSubColTag(lambda match:
                    u"<col %s>" % match.group(1).strip(), element)
        super(HackedRstTranslatorList, self).append(element)


class HackedRstTranslator(rst.MoinTranslator):
    # We need to explicitly save the parent's __init__ method to avoid
    # infinite recursion... Dynamic languages are kewl :-P
    old__init__ = rst.MoinTranslator.__init__

    def __init__(self, *arg, **kw):
        self.old__init__(*arg, **kw)
        self.body = HackedRstTranslatorList()


@hook
def patch_rstTranslator():
    """
    Monkey-Patch which makes the MoinMoin docutils HTML writer handle
    proper creation of HTML <col> and <colgroup> elements (i.e. without
    closing tags with "/>") by installing a bypassed method in the writer.
    """
    rst.MoinTranslator = HackedRstTranslator


