"""
decorators module
"""

#from django.shortcuts import resolve_url
from functools import wraps
from django.http import HttpResponse, Http404
from django.utils.functional import wraps
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.shortcuts import render_to_response
from django.template import RequestContext

from django.contrib.auth.views import redirect_to_login
from django.conf import settings

from models import Forum, Topic


def can_read_forum(view):    
    """
    Checks if a forum is readable
    Note that forum must be passed with 'pk' arg
    #TODO: redirect to a "restricted forum template"
    """
    @wraps(view)
    def inner_decorator(request, *args, **kwargs):
        pk = kwargs['pk']
        login_url = kwargs.get('login_url',None)
        redirect_field_name = kwargs.get('redirect_field_name', REDIRECT_FIELD_NAME)
        
        try:
            forum = Forum.objects.get(pk=pk)
            can_read = forum.readable_by(request.user)
            if can_read:
                return view(request,  *args, **kwargs)
        
        except Forum.DoesNotExist:
            raise Http404()
        
        except Exception, e:
            raise
            
        path = request.get_full_path()
        resolved_login_url = login_url or settings.LOGIN_URL
        
        context = RequestContext(request)
        return render_to_response("pybb/access_denied.html", {}, context_instance=context)
        
        """
        return redirect_to_login(
            path, resolved_login_url, redirect_field_name)
        """
            
            
    return inner_decorator



def can_write_topic(view):    
    """
    Checks if a user can write a forum to the topic
    Note that forum must be passed with forum_id arg
    """
    @wraps(view)
    def inner_decorator(request, *args, **kwargs):

        login_url = kwargs.get('login_url',None)
        redirect_field_name = kwargs.get('redirect_field_name', REDIRECT_FIELD_NAME)
        pk = kwargs.get('forum_id', None)
        
        if not pk:
            tpk = kwargs.get('topic_id', None)
            topic = Topic.objects.get(pk=tpk)
            forum = topic.forum
        
        else:
            try:
                forum = Forum.objects.get(pk=pk)
                
            except Forum.DoesNotExist:
                raise Http404()
            
            except Exception, e:
                raise
        
        can_write = forum.writable_by(request.user)
        if can_write:
            return view(request,  *args, **kwargs)
            
        path = request.get_full_path()
        resolved_login_url = login_url or settings.LOGIN_URL
        
        return redirect_to_login(
            path, resolved_login_url, redirect_field_name)
            
            
    return inner_decorator