# -*- coding: iso-8859-1 -*-
"""
    MoinMoin - BlurpSearch Macro

    just a modified FullSearch.

    [[BlurpSearch(term, prefix)]]
        A category serach, but only for pages beginning with prefix.
        If a ##BLURP pragma is on the page, it's contents are displayed
        after the match.
        The page links are shortened by the given prefix.
        The Category is only matched if exactly after a '----' line!

    @copyright: 2004 by Oliver Graf <ograf@bitart.de>
    @license: GNU GPL, see COPYING for details.
"""

# Imports
import re, urllib
from MoinMoin import wikiutil
from MoinMoin.Page import Page

_blurp_re = r'^##BLURP (.+)$'
_search_re = r'^----\n.*\b%s\b.*$'

Dependencies = ["pages"]

def execute(macro, text, blurp_re=re.compile(_blurp_re, re.M)):
    _ = macro.request.getText

    if text:
        parts = re.split('\s*,\s*',text,1)
        if len(parts)==1:
            needle = parts[0]
            prefix = ''
        else:
            needle = parts[0]
            prefix = parts[1]
    else:
        needle = macro.formatter.page.page_name
        prefix = ''

    # do the search
    pagecount, hits = wikiutil.searchPages(needle, literal=1, context=0)

    # generate the result
    result = []
    result.append(macro.formatter.number_list(1))
    sre = re.compile(_search_re%(needle,),re.M)
    for (count, pagename, dummy) in hits:
        if not macro.request.user.may.read(pagename):
            continue
        if pagename == macro.formatter.page.page_name:
            continue
        if prefix and not pagename.startswith(prefix):
            continue
        text=Page(pagename).get_raw_body()
        if not sre.search(text):
            continue
        result.append(macro.formatter.listitem(1))
        result.append(wikiutil.link_tag(macro.request,
            '%s?action=highlight&value=%s' % (
                wikiutil.quoteWikiname(pagename),
                urllib.quote_plus(needle)),
            pagename[len(prefix):]))
        blurp=None
        m=blurp_re.search(text)
        if m is not None:
            blurp=m.group(1)
        if blurp:
            result.append(': %s'%(blurp))
        result.append(macro.formatter.listitem(0))
    result.append(macro.formatter.number_list(0))

    return ''.join(result)

