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

    [[FarmFullSearch]]
        displays a search dialog, as it always did.

    [[FarmFullSearch(Help)]]
        embeds a search result into a page, as if you entered
        'Help' into the search box.

    @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 re, time
import xmlrpclib
from MoinMoin import config, wikiutil, search
from farmconfig import wikis

Dependencies = ["pages"]

def execute(macro, needle):
    request = macro.request
    _ = request.getText

    # If no args given, invoke "classic" behavior
    # Does not work yet since action=farmfullsearch is missing
    if needle is None:
        return searchbox(macro)

    # With empty arguments, show error message
    elif needle == '':
        err = err = _('Please use a more selective search term instead of '
                '{{{"%s"}}}') %  needle
        return '<span class="error">%s</span>' % err

    # With whitespace argument, show error message like the one used in the search box
    elif needle.isspace():
        err = _('Please use a more selective search term instead of '
                '{{{"%s"}}}') %  needle
        return '<span class="error">%s</span>' % err

    needle = needle.strip()

    # Search wiki farm and return the results
    return searchfarm(macro, needle)


def searchfarm(macro, args):
    request = macro.request
    _ = request.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



def searchbox(self):
        """ Make a search box (taken from wikimacro.py)


        @rtype: unicode
        @return: search box html fragment
        """
        _ = self._
        if self.form.has_key('value'):
            default = wikiutil.escape(self.form["value"][0], quote=1)
        else:
            default = ''

        button = _("Search Text")

        html = [
            u'<form method="get" action="">',
            u'<div>',
            u'<input type="hidden" name="action" value="farmfullsearch">',
            u'<input type="hidden" name="titlesearch" value="fullsearch">',
            u'<input type="text" name="value" size="30" value="%s">' % default,
            u'<input type="submit" value="%s">' % button,
            u'</div>',
            u'</form>',
            ]
        html = u'\n'.join(html)
        return self.formatter.rawHTML(html)






