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

    This is the backend of the issue search form.
    
    @copyright: (c) 2001 by Jürgen Hermann <jh@web.de>
    @copyright: (c) 2005 by Gary V. Vaughan <gary@gnu.org>
    @license: GNU GPL, see COPYING for details.
"""

from MoinMoin.Page import Page
from MoinMoin import wikiutil
from MoinMoin.formatter.text_html import Formatter

def execute(pagename, request, fieldname='value'):
    _ = request.getText

    # Get other form parameters
    needle = request.form.get(fieldname, [''])[0]

    # check for sensible search term
    stripped = needle.strip()
    if len(stripped) == 0:
        request.theme.add_msg(_('Please use a more selective search term instead '
                'of {{{"%s"}}}', wiki=True) % wikiutil.escape(needle), "error")
        Page(request, pagename).send_page() 
        return

    needle = "r:\\bIssue\\b.*\\b%s\\b" % stripped

    # search the pages
    from MoinMoin.search import searchPages, QueryParser
    try:
        query = QueryParser(case=0, regex=0,
                            titlesearch=0).parse_query(needle)
        results = searchPages(request, query, 'weight')
    except ValueError: # catch errors in the search query
        request.theme.add_msg(_('Your search query {{{"%s"}}} is invalid. Please refer to '
                'HelpOnSearching for more information.', wiki=True, percent=True) % wikiutil.escape(stripped), "error")
        Page(request, pagename).send_page()
        return

    # directly show a single hit
    # Note: won't work with attachment search
    # improve if we have one...
    if len(results.hits) == 1:
        page = results.hits[0]
        if not page.attachment: # we did not find an attachment
            page = Page(request, page.page_name)
            url = page.url(request, querystr={})
            request.http_redirect(url)
            return
    elif not results.hits: # no hits?
        f = request.formatter
        querydict = wikiutil.parseQueryString(request.query_string)
        querydict.update({'titlesearch': 0})

        request.theme.add_msg(_('Your search for Issue {{{"%s"}}} didn\'t return any results. '
                'Please change some terms and refert to HelpOnSearching for '
                'more information.', wiki=True, percent=True) % wikiutil.escape(stripped), "error")
        Page(request, pagename).send_page()
        return

    # send http headers
    request.emit_http_headers()

    # This action generate data using the user language
    request.setContentLanguage(request.lang)

    request.theme.send_title(_('Issue Search: "%s"') % stripped, form=request.form,
                             pagename=pagename)
    
    # Start content (important for RTL support)
    request.write(request.formatter.startContent("content"))

    # First search stats
    request.write(results.stats(request, request.formatter, 0))

    # Then search results
    output = results.pageList(request, request.formatter, info=1)        
    request.write(output)

    # End content and send footer
    request.write(request.formatter.endContent())
    request.theme.send_footer(pagename)
    request.theme.send_closing_html()
