from functools import wraps
from django.contrib import messages
from django.shortcuts import redirect
from django.http import HttpResponse, JsonResponse
from django.contrib.auth import authenticate, login
from rest_framework.authtoken.models import Token
from django.contrib.auth.models import User
import base64
from django.shortcuts import get_object_or_404
def Custom_is_staff_function(user):
    if user.is_staff:
        return True
    return False
def is_staff_access(view_to_return="index"):
    def decorator(view):
        @wraps(view)
        def _wrapped_view(request, *args, **kwargs):
            if not Custom_is_staff_function(request.user):
                messages.error(request, "No es personal del staff autorizado.")
                return redirect(view_to_return)
            return view(request, *args, **kwargs)
        return _wrapped_view
    return decorator

#--------------------Auth basica 
def auth_basic(request,*args, **kwargs):    
    if request.META['CONTENT_TYPE'] == 'application/json' and 'HTTP_AUTHORIZATION' in request.META.keys():    
        authmeth, auth = request.META['HTTP_AUTHORIZATION'].split(' ', 1)
        if authmeth.lower() == 'token':
            tokenA,user = auth.split(':', 1)            
            user = base64.b64decode(user)
            user = user.decode('utf-8')            
            token = get_object_or_404(Token, key=tokenA)
            if token and str(token.user)==user:            
                return True                            
            #user= authenticate(username=token.user, password=pwd) 
            # print('user.is_authenticated',user.is_authenticated)
            #if user.is_authenticated:
            #    return True
            else:
                return False
        return False
    elif request.META['CONTENT_TYPE'] == 'application/json' and 'HTTP_AUTHORIZATION' not in request.META.keys():  
        return request.user.is_authenticated
    else:
        return False


def http_basic_auth():        
    def decorator(view):
        @wraps(view)
        def _wrapped_view(request,*args, **kwargs):
            if not auth_basic(request,*args, **kwargs):                
                return JsonResponse({'Error':'las credenciales Token:user(base64) son incorrectas.'},status=401)
            return view(request, *args, **kwargs)
        return _wrapped_view
    return decorator