# -*- coding: iso-8859-1 -*-
"""
    MoinMoin - RandomPageContaining Macro
    modified by Jonathan C .Dietrich
    @copyright: 2000 by Jürgen Hermann <jh@web.de>
    @license: GNU GPL, see COPYING for details.

        [[RandomPageContaining(pattern,num,ignoreTitlePattern)]]
                pattern: a regex. pages will only be considered their contents match this
                num: a number. this is the number of pages to return
                ignoreTitlePattern: a regex. pages will not be included if their TITLE  matches this
                
                
                [[RandomPageContaining(,3,.*[oO])]]  3 random pages that do not include the letter o
                [[RandomPageContaining(MyCategory,1,.*MoinEditorBackup|.*Template)]] find 1 random page in MyCategory but do not inlcude templates or editor backups

"""

# Imports
import whrandom, re
from MoinMoin import config, wikiutil

Dependencies = ["time"]
_arg_links = r',\s*(?P<links>\d*)'
_arg_ignore = r',\s*(?P<ignore>[^,]+)'
_args_re_pattern = r'^(?P<pattern>[^,]+)?((%s)?(%s)?)?$' % (_arg_links,_arg_ignore)

def execute(macro, text, args_re=re.compile(_args_re_pattern)):

    ret = ''
  #  all_pages = wikiutil.getPageList(config.text_dir)

#   parse and check arguments
    args = args_re.match(text)
    if not args:
        return ('<p><strong class="error">%s</strong></p>' %
            _('Invalid include arguments "%s"!')) % (text,)

    if args.group('pattern') is not None:
        filter_regex = args.group('pattern')

#       Return a (filtered) list of pages names.
        if filter_regex:
           matching_pages = wikiutil.searchPages(filter_regex)
           matching_pages = matching_pages[1]
#       Clean the list
           cleanlist = []
        while len(matching_pages) > 0:
                cleanlist.append(matching_pages[0][1])
                del matching_pages[0]
    else:
        cleanlist = wikiutil.getPageList(config.text_dir)

#       Filter out the ignored list
    if args.group('ignore') is not None:
        ignorefilter = '(?!' +  args.group('ignore') + ')'
        cond = re.compile(ignorefilter).match
        cleanlist = filter(cond, cleanlist)

    # get number of wanted links
    try:
        links = max(int(args.group('links')), 1)
    except StandardError:
        links = 1

    # select the pages from the page list
    pages = []
    while len(pages) < links and cleanlist:
        page = whrandom.choice(cleanlist)
        if macro.request.user.may.read(page):
            pages.append(page)
        cleanlist.remove(page)

    # return a single page link
    if links == 1: return macro.formatter.pagelink(pages[0], generated=1)

    # return a list of page links
    pages.sort()
    result = macro.formatter.bullet_list(1)
    for name in pages:
        result = result + macro.formatter.listitem(1)
        result = result + macro.formatter.pagelink(name, generated=1)
        result = result + macro.formatter.listitem(0)
    result = result + macro.formatter.bullet_list(0)

    return result
