# -*- coding: iso-8859-1 -*-
"""
    MoinMoin - "FreemindSitemap" action

    Create a freemind mind map of your wiki's structure.

    @copyright: 2009 Josef Meier <jo.meier@gmx.de>
    @license: GNU GPL, see COPYING for details.
"""

import xml.etree.ElementTree as ElementTree
import StringIO
import re

from MoinMoin import wikiutil
from xml.etree.ElementTree import tostring

def getSortedPagelist(request):
    pagelist = request.rootpage.getPageList(include_underlay=False)
    pagelist.sort()
    return pagelist


def pagelist2freemind(request, pagelist):
    map = ElementTree.Element("map")
    map.set("version", "0.7.1")

    # Create the root element of our wiki xml tree
    root = ElementTree.SubElement(map, "node")
    sitemapText = "Sitemap"
    root.set("TEXT", sitemapText)

    for idx, name in enumerate(pagelist):
        if wikiutil.isSystemPage(request, name):
            continue
        if not request.user.may.read(name):
            continue

        pages = name.rsplit("/")
        currNode = root
        for page in pages:
            children = currNode.getchildren()

            found = False
            for child in children:
                if child.get("TEXT") == page:
                    currNode = child
                    found = True
                    break

            if not found:
                newNode = ElementTree.SubElement(currNode, "node")
                newNode.set("TEXT", page)
                newNode.set("LINK", name.encode("utf-8"))
                currNode = newNode

    # Print xml structure to string variable.
    stringIO = StringIO.StringIO()
    tree = ElementTree.ElementTree(map)
    tree.write(stringIO)
    freemindFormat = stringIO.getvalue()
    return freemindFormat


def getSiteMapFreemind(pagename, request):
    pagelist = getSortedPagelist(request)
    return pagelist2freemind(request, pagelist)


def execute(pagename, request):
    result = getSiteMapFreemind(pagename, request)
    request.mimetype = 'text/xml'
    request.write("""<?xml version="1.0"?>""")
    request.write(result)

