#!/usr/bin/env python

import xml.dom.minidom
import xml.xpath
import xml.xpath.Context
from xml.sax.saxutils import unescape
import sys

class DocStringGetter:
    functionXPath = '//root/function[@name="%s"]'
    descriptionXPath = functionXPath + '/description'
    parameterXPath = functionXPath + '/parameters/parameter'
    classXPath = '//root/class[@name="%s"]'
    classDescXPath = classXPath + '/description'

    def __init__(self, xmlFile):
        document = xml.dom.minidom.parse(xmlFile)
        self.context = xml.xpath.Context.Context(document.documentElement)
        self.fileName = xmlFile

    @staticmethod
    def _makeCString(s):
        rep = repr(unescape(s)).strip("'\"u")
        for before,after in [('"', '\\"'), ('\n', '\\n'), ('@', ''), ('#', '')]:
            rep = rep.replace(before,after)
        return '"%s"' % rep
       

    def getOriginalDocParameterList(self, functionName):
        element = xml.xpath.Evaluate(self.parameterXPath % functionName,
                                     context=self.context)
        return map(lambda x: x.getAttribute("name"), element)

    @staticmethod
    def getParameterList(meth):
        """Returns a list of strings containing the names of the parameters of
        functionName"""
        return map(lambda x: x.pname, meth.params)

    def getPrototype(self, meth, functionName):
        param_list = DocStringGetter.getParameterList(meth)
        original_param_list = self.getOriginalDocParameterList(functionName)

        if len(original_param_list) > len(param_list):
            object_prefix = "%s." % original_param_list[0]
        else:
            object_prefix = ""

        if meth.ret and (meth.ret != "none"):
            # yeah, that replace is quite a hack...
            ret_suffix = " -> %s" % meth.ret.replace("Pgm", "pgm.")
        else:
            ret_suffix = ""

        return "%s%s(%s)%s\n" % (object_prefix, meth.name, \
                         ", ".join(DocStringGetter.getParameterList(meth)), \
                         ret_suffix)

    def _getContentFromXPath(self, xpath, name):
        element = xml.xpath.Evaluate(xpath % name, context=self.context)
        try:
            doc_string = "\n" + element[0].firstChild.data.strip()
        except IndexError:
            print >> sys.stderr, "The entity %s is not documented in %s" % (
                                                  name, self.fileName)
            doc_string = ""
        return doc_string

    def getFunctionDocString(self, meth, functionName):
        doc_string = \
                 self._getContentFromXPath(self.descriptionXPath, functionName)

        prototype = self.getPrototype(meth, functionName)

        return DocStringGetter._makeCString( prototype + doc_string)

    def getClassDocString(self, name):
        doc_string = self._getContentFromXPath(self.classDescXPath, name)

        return DocStringGetter._makeCString(doc_string)

