# Copyright (c) 2002-2008 Infrae. All rights reserved.
# See also LICENSE.txt
# Zope 2
from AccessControl import getSecurityManager
# Zope 3
from zope.interface import implements
# Silva
from Products.Silva.SilvaPermissions import ChangeSilvaContent
# SilvaLayout
from Products.SilvaLayout import interfaces

class Metadata:
    
    implements(interfaces.IMetadata)
    
    def __init__(self, context):
        self.context = context
        self._metadataservice = self.context.aq_inner.service_metadata
        self._binding = None

    def __call__(self, setid, elementid):
        return self._getValue(setid, elementid)
        
    def __getitem__(self, setid):
        return MetadataSet(self, setid)
        
    def _getValue(self, setname, elementname):
        context = self.context.aq_inner
        content = context.get_viewable()
        # XXX nasty hack to get the editable metadata in case of preview
        url = context.REQUEST['URL'].split('/')
        if 'preview_html' in url or 'tab_preview' in url:
            sm = getSecurityManager()
            if sm.checkPermission(ChangeSilvaContent, context):
                content = context.get_editable()
        if content is None:
            return None
        return self._metadataservice.getMetadataValue(
            content, setname, elementname)

class GhostMetadata:
    """Apparently getMetadataValue does not work with Ghosts.

    This is because Ghosts get custom access handlers and generally are
    very magic. We work around this by using the non-fast-path in the
    metadata system which should work properly with Ghosts.
    """
    
    implements(interfaces.IMetadata)
    
    def __init__(self, context):
        self.context = context
        self._metadataservice = self.context.aq_inner.service_metadata
        
        content = context.get_viewable()
        # XXX nasty hack to get the editable metadata in case of preview
        url = context.REQUEST['URL'].split('/')
        if 'preview_html' in url or 'tab_preview' in url:
            sm = getSecurityManager()
            if sm.checkPermission(ChangeSilvaContent, content):
                content = context.get_editable()
        if content is None:
            self._binding = None
        else:
            self._binding = self._metadataservice.getMetadata(content)

    def __call__(self, setid, elementid):
        return self._getValue(setid, elementid)
        
    def __getitem__(self, setid):
        return MetadataSet(self, setid)
        
    def _getValue(self, setname, elementname):
        if self._binding is None:
            return None
        return self._binding.get(setname, elementname)

class MetadataSet:
    
    implements(interfaces.IMetadataSet)
    
    def __init__(self, metadata, setid):
        self.metadata = metadata
        self.setid = setid
        
    def __getitem__(self, elementid):
        return self.metadata._getValue(self.setid, elementid)
            
