import time
from thread import allocate_lock
from Products.CacheSetup.config import MACRO_CACHE_SIZE, MACRO_CACHE_AGE
_marker = []

class StupidCache:

    def __init__(self, max_size=MACRO_CACHE_SIZE, max_age=MACRO_CACHE_AGE):
        self.max_size = max_size
        self.max_age = max_age
        self.cache = {}
        self.writelock = allocate_lock()
        
    def set(self, key, value):
        # cache is about to be full - blow it away
        if len(self.cache) > self.max_size-2:
            self.clear()
        self.writelock.acquire()
        try:
            self.cache[key] = (value, time.time())
        finally:
            self.writelock.release()

    def get(self, key, default):
        v,t = self.cache.get(key, (_marker, None))
        if v is _marker:
            return default
        if t and time.time()-t > self.max_age:
            self.writelock.acquire()
            try:
                del self.cache[key]
            finally:
                self.writelock.release()
            return default
        return v

    def clear(self):
        self.writelock.acquire()
        try:
            self.cache = {}
        finally:
            self.writelock.release()
