
import sys

def ClassCache():
    return g_cache

from Ft.Ods import Exception

class _ClassCache:

    def __init__(self):
        self.__classes = {}
        self.__ids = {}

    def getClass(self,adapter,db,classId):

        #FIXME Uptodate checks???
        #if self.__classes.has_key(classId):
        #    return self.__classes[classId]

        rt = adapter.getPythonClass(db,classId)
        if rt is None:
            raise Exception.FtodsInvalidPythonClass(classId = classId)

        modName,className = rt
        if sys.modules.has_key(modName):
            klass = getattr(sys.modules[modName],className)
        else:
            klass = getattr(__import__(modName,globals(),locals(),'*'),className)
        self.__classes[classId] = klass
        self.__ids[klass] = classId
        return klass

    def getClassId(self,klass):
        #if self.__ids.has_key(klass):
        #    return self.__ids[klass]
        return None

    def registerClassId(self,id_,klass):
        self.__classes[id_] = klass
        self.__ids[klass] = id_

    def purgeAll(self):
        self.__classes = {}
        self.__ids = {}
        


g_cache = _ClassCache()
del _ClassCache
