from simple import CacheMgr as SimpleCacheMgr
from django.utils.encoding import force_unicode
from pycon.core import safe_utf8_encode
import time, pickle
import datetime

class CacheMgr(SimpleCacheMgr):
    """Local Memory Cache - Thread-safe in-memory cache backend.
    """
    scheme = 'locmem'

    def info(self):
        self.cache._lock.reader_enters()
        res = super(CacheMgr, self).info()
        self.cache._lock.reader_leaves()
        return res

    def __iter__(self):
        lock = self.cache._lock
        lock.reader_enters()
        expire = self.cache._expire_info.items()
        lock.reader_leaves()
        cache = self.cache._cache
        expire.sort(cmp=lambda a, b: cmp(a[1], b[1]))
        now = time.time()
        for key, exp in expire:
            lock.reader_enters()
            try:
                raw = cache[key]
            except KeyError:
                continue
            finally:
                lock.reader_leaves()
            yield self._cache_info(key, raw, exp)

    def clear(self):
        self.cache._lock.writer_enters()
        try:
            super(CacheMgr, self).clear()
        finally:
            self.cache._lock.writer_leaves()
