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

    @copyright: 2006 by Oliver Siemoneit
    @license: GNU GPL, see COPYING for details.

    FarmFullSearch is heavily based on FullSearch
    @copyright: 2000-2004 by Jürgen Hermann <jh@web.de>
    @license: GNU GPL, see COPYING for details.

    Changes:
    * 2006-11-18 (DavidLinke) Handle failure of xmlrpc request gracefully
                 Failure is expected e.g. when authentication is required.
"""

import time
import xmlrpclib
from MoinMoin.Page import Page
from MoinMoin import wikiutil
from MoinMoin.util import MoinMoinNoFooter
from farmconfig import wikis


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

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

    # check for sensible search term
    striped = needle.strip()
    if len(striped) == 0:
        err = _('Please use a more selective search term instead '
                'of {{{"%s"}}}') % needle
        # send http headers
        request.http_headers()
        Page(request, pagename).send_page(request, msg=err)
        return

    # search the pages
    results = searchfarm(request, needle)

    # send http headers
    request.http_headers()

    # This action generate data using the user language
    request.setContentLanguage(request.lang)
    title = _('Fulll Text Search: "%s"')
    wikiutil.send_title(request, title % needle, form=request.form,
                        pagename=pagename)

    # Start content (important for RTL support)
    request.write(request.formatter.startContent("content"))

    request.write(results)

    # End content and send footer
    request.write(request.formatter.endContent())
    wikiutil.send_footer(request, pagename)


def searchfarm(macro, args):
    _ = macro.getText
    output = ""
    searchterm = args

    for wiki in wikis:
        searchresults = []
        #Code partly taken from wikilist.py by TheAnarcat!
        name = wiki[0]
        url = wiki[1]
        from re import sub
        # XXX, hack: transform the regexp into a canonical url
        # we need canonical urls in the config for this to be clean
        # look for (foo|bar) and replace with foo
        url = sub('\(([^\|]*)(\|[^\)]*\))+', '\\1', url)
        # remove common regexp patterns and slap a protocol to make this a real url
        url = 'http://' + sub('[\^\$]|(\.\*)', '', url)
        # for farmsearch we additionally need a slash at the end
        url = url + '/'

        # Set the url for the remote farm wiki here. Note: Slash at the end is needed
        #url = "http://wikifarm.koumbit.net/"
        srcwiki = xmlrpclib.ServerProxy(url + '?action=xmlrpc2')

        start = time.time()
        try:
            searchresults = srcwiki.searchPages(searchterm)
            # This is a bad and time consuming solution just to get the number of pages searched
            allpages = srcwiki.getAllPages()
        except xmlrpclib.ProtocolError:
            output += macro.formatter.paragraph(1)
            output += macro.formatter.text('Failed to perform search in %s' %
                                           url)
            output += macro.formatter.paragraph(0)
            continue

        output += macro.formatter.paragraph(1)
        #output += macro.formatter.text(_("%s (%d results)") %(url, len(searchresults)))
        output += macro.formatter.strong(1)
        output += macro.formatter.text(name)
        output += macro.formatter.strong(0)
        output += macro.formatter.linebreak(0)
        output += macro.formatter.text(_("%(hits)d results out of about %(pages)d pages.") %
                       {'hits': len(searchresults), 'pages': len(allpages)})
        elapsed = time.time() - start
        output += macro.formatter.text(u' (%s)' % macro.formatter.text(_("%.2f seconds") % elapsed))

        output += macro.formatter.paragraph(0)


        for searchresult in searchresults:

            output += macro.formatter.div(1, css_class='searchresults')
            output += macro.formatter.definition_list(1)

            output += macro.formatter.definition_term(1)
            output += macro.formatter.url(1, url + searchresult[0] + '?highlight=' + searchterm)
            output += macro.formatter.text(searchresult[0])
            output += macro.formatter.url(0)
            output += macro.formatter.definition_term(0)

            output += macro.formatter.definition_desc(1)
            output += macro.formatter.small(1)
            output += macro.formatter.rawHTML(searchresult[1])
            output += macro.formatter.small(0)
            output += macro.formatter.definition_desc(0)

            output += macro.formatter.definition_list(0)
            output += macro.formatter.span(0)

        output += macro.formatter.linebreak(0)
        output += macro.formatter.linebreak(0)
        output += macro.formatter.linebreak(0)

    return output


