# Copyright (c) 2002-2005 Infrae. All rights reserved.
# See also LICENSE.txt

from Globals import InitializeClass, package_home
from AccessControl import ClassSecurityInfo
from OFS import SimpleItem

from Products.PageTemplates.PageTemplateFile import PageTemplateFile

from Products.Formulator.Form import ZMIForm

from Products.Silva import SilvaPermissions as permissions
from Products.Silva import helpers
from Products.SilvaOAI.silvaoai import Query

from Products.SilvaDocumentLibrary.restrictedquery import QueryRestriction

class DocumentSearch(QueryRestriction, Query):
 
    """Allows for public searches for the Document Library
    """
    
    meta_type = 'Document Library Search'
    
    security = ClassSecurityInfo()

    def __init__(self, id, title, service):
        Query.__init__(self, id, title, service)
        self._metadata_format = 'dl'

    security.declareProtected(
        permissions.AccessContentsInformation, 'getSearchForm')
    def getSearchForm(self, advanced=None):
        # XX Overriding this method should probably not be needed - 
        # IOW, probably needs some refactoring in OAICore/SilvaOAI
        # Likewise, the method need to accept a 'advanced' keyword, that
        # is not used in this implementation. At least not now.
        search_form = ZMIForm('search_form', 'Search Form', 1)
        self.addSearchFields(search_form)
        self.updateSearchForm(search_form)
        return search_form.__of__(self)
    
    security.declareProtected(
        permissions.AccessContentsInformation, 'getCommonFOITopics')
    def getCommonFOITopics(self, results, max=5):
        # Run through the result set, look at the metadata_foi_topics
        # attribute and determine what categories are most common
        # in this set.
        count_for_foi_topic = {}
        for brain in results:
            foi_topics = brain['metadata_foi_topic']
            if foi_topics is None:
                continue
            foi_topic = foi_topics[0] # should be one item in the list anyway
            count = count_for_foi_topic.get(foi_topic, 0)
            count_for_foi_topic[foi_topic] = count + 1
        flattened = count_for_foi_topic.items()
        if len(flattened) <= max:
            return count_for_foi_topic.keys()
        def t_cmp(t1, t2):
            # from big to small, so reverse comparator
            return cmp(t2[1], t1[1])
        flattened.sort(t_cmp)
        top_so_many = [t[0] for t in flattened[:max]]
        top_so_many.sort()
        return top_so_many
        
InitializeClass(DocumentSearch)    
    
manage_addQuerySourceForm = PageTemplateFile(
    "www/OAIQueryForm", globals(), __name__='manage_addQuerySourceForm')
    
def manage_addDocumentSearch(context, id, title, service, REQUEST=None):
    query = DocumentSearch(id, title, service)
    # XXX needs id validation
    context._setObject(id, query)
    query = getattr(context, id)
    query.set_title(title)
    helpers.add_and_edit(context, id, REQUEST)
    return query
