##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# Copyright (c) 2007 Nexedi SA
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
##############################################################################

"""This patch is for importing Business Templates generated by Zope 2.8
into Zope 2.7.

In Zope 2.7, the class of an object was represented by a tuple (module, name),
but this has been changed to just a class name itself.
"""

try:
    # This portion depends on ZODB, so the version test is based on
    # the ZODB's structure. In ZODB 3.4 and later, the object serialization
    # is segregated to serialize.py, while it is in Connection.py in ZODB 3.2.
    from ZODB import serialize
    del serialize
except ImportError:
    from ZODB.Connection import Connection, StringIO, Unpickler, ExtensionKlass

    def __getitem__(self, oid, tt=type(())):
        obj = self._cache.get(oid, None)
        if obj is not None:
            return obj

        __traceback_info__ = (oid)
        p, serial = self._storage.load(oid, self._version)
        __traceback_info__ = (oid, p)
        file=StringIO(p)
        unpickler=Unpickler(file)
        unpickler.persistent_load=self._persistent_load

        object = unpickler.load()

        # <patch author="yo">
        if type(object) is tt:
            klass, args = object
        else:
            klass = object
            args = None
        # </patch>

        if type(klass) is tt:
            module, name = klass
            klass=self._db._classFactory(self, module, name)

        if (args is None or
            not args and not hasattr(klass,'__getinitargs__')):
            object=klass.__basicnew__()
        else:
            object = klass(*args)
            if klass is not ExtensionKlass:
                object.__dict__.clear()

        object._p_oid=oid
        object._p_jar=self
        object._p_changed=None
        object._p_serial=serial

        self._cache[oid] = object
        return object

    Connection.__getitem__ = __getitem__
