

import time

from Ft.Ods import LocalThreading


def GlobalCache():
    return g_gc



class _GlobalCache:

    def __init__(self):
        self.__objectCache = {}

        self.__lock = LocalThreading.RLock()


    def purge(self,dbName,testTime):
        self.__lock.acquire()
        try:
            for _type,data in self.__objectCache.get(dbName,{}).items():
                toDelete = filter(lambda x,t=testTime: x[1][0] < t,data.items())
                for t in toDelete:
                    del data[t[0]]
        finally:
            self.__lock.release()
                

    def purgeAll(self):
        self.__lock.acquire()
        try:
            self.__objectCache = {}
        finally:
            self.__lock.release()
        

    def registerObject(self,dbName,typ,id_,args):
        self.__lock.acquire()
        try:
            if not self.__objectCache.has_key(dbName):
                self.__objectCache[dbName] = {}
            if not self.__objectCache[dbName].has_key(typ):
                self.__objectCache[dbName][typ] = {}
            
            self.__objectCache[dbName][typ][id_] = (time.time(),args)
        finally:
            self.__lock.release()

    def getObject(self,dbName,adapter,db,typ,id_):
        self.__lock.acquire()
        try:
            if not self.__objectCache.has_key(dbName):
                return None
            if not self.__objectCache[dbName].has_key(typ):
                return None
            if not self.__objectCache[dbName][typ].has_key(id_):
                return None
            #Up todate check
            if adapter.objectUptoDate(db,typ,id_,self.__objectCache[dbName][typ][id_][0]):
                return self.__objectCache[dbName][typ][id_][1]
            del self.__objectCache[dbName][typ][id_]
            return None
        finally:
            self.__lock.release()
        
                             


g_gc = _GlobalCache()

del _GlobalCache
