from Acquisition import aq_base, Implicit
from AccessControl import ClassSecurityInfo
from Interface import Interface
from Interface.Implements import objectImplements
from OFS.SimpleItem import SimpleItem
from ZODB.PersistentMapping import PersistentMapping

from Compatibility import UniqueObject, getToolByName

ANNOTATION_MARKER = '_portal_annotations_'

class IAnnotable(Interface): pass

class ComponentError(Exception): pass

class AnnotationTool(UniqueObject, SimpleItem):

    id = 'portal_annotations'
    title = 'Annotations'
    meta_type = 'Portal Annotations'

    security = ClassSecurityInfo()

    manage_options = SimpleItem.manage_options

    def __init__(self):
        pass

    def getAnnotations(self, object, namespace_key):

        annotations = getattr(aq_base(object), ANNOTATION_MARKER, None)
        if annotations is None:
            if objectImplements(object, IAnnotable):
                annotations = Annotations()
                setattr(object, ANNOTATION_MARKER, annotations)
            else:
                raise ComponentError("object does not support annotations")

        if not annotations.has_key(namespace_key):
            return annotations.setdefault(namespace_key, Annotations())

        return annotations[namespace_key]


class Annotations(PersistentMapping):
    pass


def getAnnotations(object, namespace_key):
    annotations = getToolByName('portal_annotations')
    return annotations.getAnnotations(object, namespace_key)
    
