from forms import form_generator
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django import template
from django.contrib.auth.decorators import user_passes_test
from pycon.features.decorators import feature_required, auth_required
from backends import cachemgr

@user_passes_test(lambda u: u.is_active and u.is_superuser)
@feature_required('EditCache', auto_create_feat=True)
def cache_list(request):

    cache_entry_list = form_generator(request.POST)
    if request.POST:
        if '__clear' in request.POST:
            cachemgr.clear()
        elif cachemgr.has_cull and '__cull' in request.POST:
            cachemgr.cull()
        elif '__delete' in request.POST:
            cache_entry_list = list(cache_entry_list)
            for entry in cache_entry_list:
                entry['form'].maybe_delete()
        return HttpResponseRedirect(request.path)
    return render_to_response('cachemgr/cache_list.html',
                              {'cache_list': cache_entry_list,
                               'cachemgr': cachemgr,
                               'title': 'Cache Manager'},
                              context_instance=template.RequestContext(request))
