import StructuredText
import string

# I'm attempting to use the StructuredText structure here to pick out
# values and attrs, but I'm really just bludgeoning them out of there.
# Maybe I'm just not familiar enough with the ST structure.
# I want a ST DOM!
def STXHeaderValue(stRaw, headerName, stripPar = None):
    """
    Extract a value from a string based on its StructuredText header.
    The colorized body associated with the first top-level
    StructuredTextSectionTitle that matches the header argument is returned,
    or None if nothing matches.
    If stripPar is true, remove the outer paragraph elements first.
    Matches are case-insensitive and ignore characters after the match.
    """
    # sections are children of the doc, headers are 1st children of
    # the sections, sub-bodies of the headers are 2:n children of the
    # sections.
    stDoc = StructuredText.Document(StructuredText.Basic(stRaw))
    headerName = string.lower(headerName)
    for child in stDoc.getChildNodes():
        header = child.getChildNodes()[0]
        body = ''
        if header.getNodeName() == 'StructuredTextSectionTitle':
            headerValue = string.strip(string.lower(header.getNodeValue()))
            headerValue = headerValue[0:len(headerName)]
            if headerValue == headerName:
                # concat HTML of rest of section for body
                for sub in child.getChildNodes()[1:]:
                    body += StructuredText.HTML(sub)
                if stripPar:
                    # XXX the right way to do this is a custom colorizer
                    body = body[string.index(body, "<p>") + 3:]
                    body = body[0:string.index(body, '</p>')]
                    body = string.strip(body)
                return body
    return None
