# -*- coding: iso-8859-1 -*-

import re
from MoinMoin import config, wikiutil

"""
    This is a MoinMoin parser plugin that can display, nicely colored,
    the Gobby 3.0 or Sobby saved session, preserving the coloring.

    Note: The session file parser is extremely primitive and hacky, and
    probably doesn't include some special cases, as it was written in 5
    minutes while just looking at a sample session file.

    Also, the code was previously a standalone filter, and was later 
    wrapped in all the MoinMoin plugin stuff -- so it has its own function
    for quoting html, and generally is very dirty.

    But at least it's some start.

    This is public domain.
"""



Dependencies = []

class Parser:
    # Enable caching
    caching = 1
    Dependencies = []

    user_re = re.compile(r'^\s*user\s+colour="(?P<color>[^"]*)"\s*id="(?P<id>\d+)"\s*name="(?P<name>[^"]*)"\s*$')
    doc_re = re.compile(r'^\s*document\s+id="(?P<id>\d+)"\s*owner="(?P<owner>\d+)"\s*title="(?P<title>[^"]*)"\s*$')
    part_re = re.compile(r'^\s*part\s+author="(?P<author>\d+)"\s*content="(?P<content>.*)"$')

    def __init__(self, raw, request, **kw):
        """Create a minimal Parser object with required attributes."""
        self.request = request
        self.form = request.form
        self.raw = raw
        
    def format(self, formatter):
        result = self.parse_gobby(self.raw)
        self.request.write(self.request.formatter.rawHTML(result))


    def quote_html(self, text):
        return text.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')

    def unquote(self, text):
        return text.replace(r'\"', '"')

    def parse_gobby(self, text):
        user_colors = {}
        user_names = {}
        docs = {}
        cur_doc = None
        cur_line = None
        for line in text.split('\n'):
            stripped = line.strip()
            if stripped=='line':
                cur_line = []
                cur_doc.append(cur_line)
            else:
                m = self.user_re.match(line)
                if m:
                    name = m.group('name')
                    user_id = int(m.group('id'))
                    color = m.group('color')
                    user_colors[user_id]=color
                    user_names[user_id]=name
                else:
                    m = self.doc_re.match(line)
                    if m:
                        title = m.group('title')
                        owner = int(m.group('owner'))
                        doc_id = int(m.group('id'))
                        docs[title] = []
                        cur_doc = docs[title]
                        cur_line = []
                        cur_doc.append(cur_line)
                    else:
                        m = self.part_re.match(line)
                        if m:
                            author = int(m.group('author'))
                            content = self.unquote(m.group('content'))
                            cur_line.append( (author, content) )
        result= '''<style type="text/css"><!--'''

        for user,color in user_colors.iteritems():
            result+= '.user%d { background-color: #%s }' % (user, color)

        result+= '''--></style>'''
        result+= '<h1>Users</h1>'
        result+= '<ul>'
        for user,name in user_names.iteritems():
            result+= '<li><span class="user%d">%s</span></li>' % (user, self.quote_html(name))
        result+= '</ul>'

        result+= '<h1>Documents</h1>'
        for title,body in docs.iteritems():
            html = ''
            for line in body:
                part_html = ''
                for part in line:
                    part_html += '<span class="user%d">%s</span>' % (part[0], self.quote_html(part[1]))
                html += '%s<br>' % part_html
            result+= '<h2>%s</h2>' % self.quote_html(title)
            result+= '<pre>%s</pre>' % html
        return result
