#coding=utf-8

from django.views.decorators.csrf import csrf_exempt
from django.utils.functional import wraps

from libs.http import ForbiddenJSONResponse
from apps.exceptions import CustomError
from .tokens import token_generator
from .models import User

def token_required(view_func):
    """Decorator which ensures the user has provided a correct user and token pair."""

    @csrf_exempt
    @wraps(view_func)
    def _wrapped_view(request, *args, **kwargs):
        user_id = request.META.get('HTTP_USER_ID')
        token = request.META.get('HTTP_ACCESS_TOKEN')

        if user_id and token:
            try:
                user = User.objects.get(pk=user_id)
            except:
                return ForbiddenJSONResponse()

            valid = token_generator.check_token(user, token)
            if valid:
                request.user = user
                return view_func(request, *args, **kwargs)

        return ForbiddenJSONResponse()
    return _wrapped_view

decorator_with_arguments = lambda decorator: lambda *args, **kwargs: lambda func: decorator(func, *args, **kwargs)

@decorator_with_arguments
def permission_required(function, perm):
    def _function(request, *args, **kwargs):
        user_id = request.META.get('HTTP_USER_ID')
        token = request.META.get('HTTP_ACCESS_TOKEN')
        if user_id and token:
            try:
                user = User.objects.get(pk=user_id)
            except:
                return ForbiddenJSONResponse()

            valid = token_generator.check_token(user, token)
            if valid:
                request.user = user
        else:
            return ForbiddenJSONResponse()

        if request.user.has_perm(perm):
            return function(request, *args, **kwargs)
        else:
            from django.contrib.auth.models import Permission
            from libs.http import JSONError
            ps = perm.split('.')
            try:
                p = Permission.objects.get(codename=ps[1], content_type__app_label=ps[0])
            except:
                return JSONError(u"权限配置错误！")

            return JSONError(u"您没有[%s-%s]权限，无法执行该操作，请联系管理员分配权限！" % (p.content_type.name, p.name))
    return _function

def valid_permission(user,perm):
    if user.has_perm(perm):
        return

    from django.contrib.auth.models import Permission
    ps = perm.split('.')
    try:
        p = Permission.objects.get(codename=ps[1], content_type__app_label=ps[0])
    except:
        raise CustomError(u"权限配置错误！")
    raise CustomError(u"您没有[%s-%s]权限，无法执行该操作，请联系管理员分配权限！" % (p.content_type.name, p.name))


def isHasPermissions(user, perm):
    if user.has_perm(perm):
        return True
    return False
