#TODO: Add license
""" This module monkeypatches the ObjectManager class of OFS.
    
    The extra functions add support for moving Topics.
"""
__version__ = "$id$"

#XXX: Is this patch necessarry any longer?

# Monkeypatching OFS.ObjectManager
import OFS

def absattr(attr):
    if callable(attr): return attr()
    return attr

if not hasattr(OFS.ObjectManager, 'absattr'):
    setattr(OFS.ObjectManager, 'absattr', absattr)

# Monkeypatching OFS.ObjectManager.ObjectManager

def cb_isCopyable(self):
    # Is object copyable? Returns 0 or 1
    if not (hasattr(self, '_canCopy') and self._canCopy(0)):
        return 0
    if hasattr(self, '_p_jar') and self._p_jar is None:
        return 0

    # So far so good, now check all children as well
    for obj in self.objectValues():
        if hasattr(obj, 'cb_isCopyable'):
            if not obj.cb_isCopyable():
                return 0

    return 1

def cb_isMoveable(self):
    # Is object moveable? Returns 0 or 1
    if not (hasattr(self, '_canCopy') and self._canCopy(1)):
        return 0
    if hasattr(self, '_p_jar') and self._p_jar is None:
        return 0
    try:    n=aq_parent(aq_inner(self))._reserved_names
    except: n=()
    if absattr(self.id) in n:
        return 0

    # So far so good, now check all children as well
    for obj in self.objectValues():
        if hasattr(obj, 'cb_isMoveable'):
            if not obj.cb_isMoveable():
                return 0

    return 1

def _notifyOfCopyTo(self, container, op=0):
    """ Overide this to be pickly about where you go! If you dont
        want to go there, raise an exception. The op variable is
        0 for a copy, 1 for a move.
    """
    for obj in self.objectValues():
        if hasattr(obj, '_notifyOfCopyTo'):
            obj._notifyOfCopyTo(container, op)

om = OFS.ObjectManager.ObjectManager

if not hasattr(om, 'cb_isCopyable'):
    setattr(om, 'cb_isCopyable', cb_isCopyable)
if not hasattr(om, 'cb_isMoveable'):
    setattr(om, 'cb_isMoveable', cb_isMoveable)
if not hasattr(om, '_notifyOfCopyTo'):
    setattr(om, '_notifyOfCopyTo', _notifyOfCopyTo)

# End Monkeypatching

