# coding: utf-8

from ig.generic.pattern.singleton import Singleton
from suds.cache import Cache
from threading import Lock


########################################################################
class MemoryCache(Cache, object):
    """
    Trivial cache for Suds.
    This cache simply caches every object in the memory for fast read access.

    Should be thread-safe.
    """
    __metaclass__ = Singleton

    #----------------------------------------------------------------------
    def __init__(self):
        self._cache = dict()
        self._lock = Lock()

    #----------------------------------------------------------------------
    def get(self, key):
        return self._cache.get(key, None)

    #----------------------------------------------------------------------
    def getf(self, key):
        raise NotImplementedError

    #----------------------------------------------------------------------
    def put(self, key, value):
        self._acquire_lock()
        try:
            self._put(key, value)
        finally:
            self._release_lock()

    #----------------------------------------------------------------------
    def _acquire_lock(self):
        self._lock.acquire()

    #----------------------------------------------------------------------
    def _put(self, key, value):
        self._cache[key] = value

    #----------------------------------------------------------------------
    def _release_lock(self):
        self._lock.release()

    #----------------------------------------------------------------------
    def putf(self, key, filep):
        raise NotImplementedError

    #----------------------------------------------------------------------
    def purge(self, key):
        self._acquire_lock()
        try:
            self._purge(key)
        finally:
            self._release_lock()

    #----------------------------------------------------------------------
    def _purge(self, key):
        try:
            del self._cache[key]
        except KeyError:
            pass

    #----------------------------------------------------------------------
    def clear(self):
        self._acquire_lock()
        try:
            self._clear()
        finally:
            self._release_lock()

    #----------------------------------------------------------------------
    def _clear(self):
        self._cache = dict()
