from django.core.cache import cache
from django.conf import settings
from guardian.core import ObjectPermissionChecker
from django.contrib.auth.models import User
from django.db.models import Q
from guardian.shortcuts import assign

def get_cached_checker(user):
    key_name = 'checker_%s' % user.username
    
    checker = cache.get(key_name)
    if checker:
        return checker
    
    checker = ObjectPermissionChecker(user)
    cache.set(key_name, checker)
    return checker


def cached_assign(perm, user_or_group, object):
    assign(perm, user_or_group, object)
    
    if hasattr(user_or_group, 'username'):
        key = 'checker_%s' % user_or_group.username
    else:
        key = 'checker_%s' % user_or_group.name
        
    cache.delete('checker_%s' % key)
    
    
def get_cached_userlist():
    userlist = cache.get('userlist')
    if userlist:
        return userlist
    
    query = Q(id=settings.ANONYMOUS_USER_ID) | Q(is_superuser=True)
    userlist = User.objects.exclude(query)
    cache.set('userlist', userlist)
    return userlist