"""
$Id: __init__.py 20738 2006-03-12 02:27:29Z plonista $
"""

from zLOG import LOG, WARNING, INFO

def log(summary='', text='', log_level=INFO):
    LOG('MemcachedManager', log_level, summary, text)


class O(dict):
    """Represents the cache for one Zope object.
    """

    def __init__(self, h):
        self.h = h

    def aggregateIndex(self, view_name, req, req_names, local_keys):
        """Returns the index to be used when looking for or inserting
        a cache entry.
        view_name is a string.
        local_keys is a mapping or None.
        """
        req_index = []
        # Note: req_names is already sorted.
        for key in req_names:
            if req is None:
                val = ''
            else:
                val = req.get(key, '')
            req_index.append((str(key), str(val)))
        if local_keys:
            local_index = []
            for key, val in local_keys.items():
                local_index.append((str(key), str(val)))
            local_index.sort()
        else:
            local_index = ()
        return hash((self.h, str(view_name),
                     tuple(req_index), tuple(local_index)))

    def getEntry(self, cache, index):
        return cache.get(index)

    def setEntry(self, cache, index, data):
        cache.set(index, data)
        if not self.has_key(index):
            self[index] = None
            cache.set(self.h, self)

    def cleanup(self, cache):
        for index in self.iterkeys():
            cache.delete(index)
        cache.delete(self.h)

def initialize(context):
    try:
        import MemcachedManager
    except ImportError:
        log('Unable to import MemcachedManager.  You may need to install memcached')
        return

    context.registerClass(
        MemcachedManager.MemcachedManager,
        constructors = (
        MemcachedManager.manage_addMemcachedManagerForm,
        MemcachedManager.manage_addMemcachedManager),
        icon="cache.gif"
        )

