"""Rule folder implementation

$Id: $
"""

__authors__ = 'Geoff Davis <geoff@geoffdavis.net>'
__docformat__ = 'restructuredtext'

import time
from AccessControl import ClassSecurityInfo
from Products.Archetypes import public as atapi
from Products.CacheSetup.content.interfaces import ICacheToolFolder
try:
    from Products.CMFCore import permissions
except ImportError:
    from Products.CMFCore import CMFCorePermissions as permissions
from stupid_cache import StupidCache # XXX upgrade me!

_caches = {}


class MacroFolder(atapi.OrderedBaseFolder):
    """A container for macro cache objects"""

    __implements__ = (atapi.OrderedBaseFolder.__implements__, ICacheToolFolder)
    
    security = ClassSecurityInfo()
    archetype_name = 'Macro Folder'
    portal_type = meta_type = 'MacroFolder'
    global_allow = 0
    allowed_content_types = ('MacroCacheRule')
    cacheable_macros = None
    cacheable_macros_valid = None

    actions = (
        {'action':      'string:$object_url/cache_setup_config',
         'category':    'object',
         'id':          'view',
         'name':        'Cache Setup',
         'permissions': (permissions.ManagePortal,),
         'visible':     False},
    )

    aliases = {
        '(Default)':    'cache_setup_config',
        'view' :        'cache_setup_config',
        'edit' :        'base_edit'
    }

    def __init__(self, obj_id):
        atapi.OrderedBaseFolder.__init__(self, obj_id)
        self.__cacheid = '%s_%f' % (id(self), time.time())

    def getCache(self):
        return _caches.setdefault(self.__cacheid, StupidCache())

    def clearCache(self):
        self.getCache().clear()

    def isCacheableMacro(self, macro_name):
        if macro_name in self._getCacheableMacros():
            return True
        return False

    def getKey(self, macro_name, request, context, container, user, template, traverse_subpath):
        macro_rule = getattr(self, self._getCacheableMacros()[macro_name], None)
        if macro_rule is None:
            return None
        return macro_rule.getKey(request, context, container, user, template, traverse_subpath) 

    def getMacroText(self, macro_name, key, default):
        return self.getCache().get((macro_name,key), default)

    def setMacroText(self, macro_name, key, text):
        self.getCache().set((macro_name,key), text)

    def _getCacheableMacros(self):
        cm = getattr(self, '_v_cacheable_macros', None)
        cm_count = getattr(self, '_v_cacheable_macros_stamp', None)
        catalog_count = self.getParentNode().getCatalogCount()

        if cm is None or cm_count is None or cm_count != catalog_count:
            self._v_cacheable_macros = {}
            for v in self.objectValues():
                if v.getEnabled():
                    self._v_cacheable_macros[v.getMacroName()] = v.getId()
            self._v_cacheable_macros_stamp = catalog_count
            cm = self._v_cacheable_macros
            
        return cm

atapi.registerType(MacroFolder)
