# 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.oaisource import QuerySource

from Products.SilvaDocumentLibrary.restrictedquery import QueryRestriction

class DocumentCherry(QuerySource, QueryRestriction):
    """Code Source-like object that accepts the handle for a
       cherry picked document, and displays the document's
       metadata.
    """
    
    meta_type = 'Document Library Cherry'

    security = ClassSecurityInfo()

    def __init__(self, id, service):
        QuerySource.__init__(self, id, service)
        self._metadata_format = 'dl'
    
    # ExternalSource
    security.declareProtected(permissions.ChangeSilvaContent, 'form')
    def form(self):
        f = ZMIForm('cherries', 'Cherries', 1)
        f.manage_addField('handle', 'Handle', 'StringField')
        field = f['handle']
        field.values['description'] = 'Handle URL for the Document'
        field.values['required'] = 1
        return f.__of__(self)
        
    security.declareProtected(
        permissions.AccessContentsInformation, 'recordForHandle')
    def recordForHandle(self, handle):
        brains = self.queryResults({'metadata_handle': handle})
        # What would it mean if I find more than 1 record for a handle?
        if len(brains) > 1:
            # XXX use logging here!
            print 'Huh, more than 1 record?', handle
        return brains[:1]
    
    security.declareProtected(
        permissions.AccessContentsInformation, 'to_html')
    def to_html(self, REQUEST, **kw):
        """Render HTML for inclusion in Silva Documents.
        """
        handle = kw.get('handle', None)
        if handle is None:
            return self.recordLayout(record=None)
        return self.recordLayout(
            results=self.recordForHandle(handle))
        
    security.declareProtected(
        permissions.AccessContentsInformation, 'recordLayout')
    def recordLayout(self, results):
        return self.public['records'](
            results=results, batching_info=False, topic_links=False)
    
InitializeClass(DocumentCherry)
        
def manage_addDocumentCherry(context, id, title, service, REQUEST=None):
    """factory
    """
    query = DocumentCherry(id, service)
    # XXX needs id validation
    context._setObject(id, query)
    query = getattr(context, id)
    helpers.add_and_edit(context, id, REQUEST)
    return query

manage_addQuerySourceForm = PageTemplateFile(
    "www/DocumentCherryForm", globals(), __name__='manage_DocumentCherryForm')

def manage_addDocumentCherryFromZMI(context, id, title, service_id, REQUEST=None):
    """factory for ZMI add
    """
    service = context.restrictedTraverse(service_id)
    return manage_addDocumentCherry(context, id, title, service, REQUEST)
