from trac.core import *
from trac.wiki.api import IWikiPageManipulator

class PlainTextWikiPagePreparer(Component):

    implements(IWikiPageManipulator)

    # Wiki page name endings that will be recognized as plain text:
    NAME_ENDING = ('.txt', '.text', '.ascii')

    # Custom CSS class name:
    CSS_CLASS = ''

    # Default CSS style:
    CSS_STYLE = 'font-family:monospace; border: 0px; box-shadow: 0 0 0; margin: 0 0; overflow: auto; white-space: pre; display: inline; margin-left: 0; padding-left: 0; '

    # Enforce class precedence over style:
    # (in HTML it's the opposite, reason why we can't use both)    
    if not CSS_CLASS:
        CSS_CLASS_OR_STYLE = ' style="' + CSS_STYLE + '"'
    else:
        CSS_CLASS_OR_STYLE = ' class="' + CSS_CLASS + '"'


    def prepare_wiki_page(self, req, page, fields):
        if self._is_special_page(page):
            fields['text'] = self._escape_wikitext(page.text)

    def validate_wiki_page(self, req, page):
        return []

    def _is_special_page(self, page):
        """Should the page be treated as special pre-formatted plain text?
        For example, let's treat special all wiki pages ending in pre-defined extensions.
        """
        return page.name.lower().endswith(self.NAME_ENDING)

    def _escape_wikitext(self, wikitext):
        # Return the escaped wikitext of a pre-formatted plain text.
        return '{{{\n#!html\n<pre' + self.CSS_CLASS_OR_STYLE + '>\n' + wikitext + '\n</pre>\n}}}';
        # below is wrong because the pre style will take precedence over our style.
        #return '{{{\n#!div' + self.CSS_CLASS_OR_STYLE + '\n{{{\n' + wikitext + '\n}}}\n}}}'

