"""
$Id: __init__.py,v 1.2 2005/02/26 17:56:10 sidnei Exp $
"""

from zope.configuration import xmlconfig
from Products.CMFCore.utils import getToolByName

try:
    from Products.Five.zcml import load_string
except:
    def load_string(s):
        """Load a snipped of ZCML into the context.

        Use with extreme care.
        """
        from Products.Five.zcml import _context
        _context = xmlconfig.string(s, _context)

def makeContent(ctxt, typ, id, *args, **kw):
    enable_global = kw.get('enable_global', False)
    if enable_global:
        old = setGlobal(ctxt, typ, True)
        del kw['enable_global']
    ctxt.invokeFactory(typ, id, *args, **kw)
    if enable_global:
        setGlobal(ctxt, typ, old)
    return ctxt._getOb(id)

def setGlobal(ctxt, typ, value=True):
    tt = getToolByName(ctxt, 'portal_types')
    old = tt.getTypeInfo(typ).global_allow
    tt.getTypeInfo(typ).global_allow = value
    return old

_uids = {}

class OrderKeeper:

    def add(self, event):
        uids = _uids.setdefault(event.sourceUID, [])
        tuid = event.targetUID
        if tuid not in uids:
            uids.append(tuid)

    def remove(self, event):
        uids = self.get(event.sourceUID)
        tuid = event.targetUID
        if tuid in uids:
            uids.remove(tuid)

    def get(self, uid):
        return _uids.get(uid, [])

    def clear(self):
        _uids.clear()

order_keeper = OrderKeeper()
reference_add = order_keeper.add
reference_remove = order_keeper.remove
