from django.urls import resolve
from django.http import HttpResponse
from .models import Usuario, Persona
from project.settings import SECRET_KEY
import jwt
import logging

class ApiMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # se omite esta regla si no es api
        if request.path[0:5] != '/api/':
            response = self.get_response(request)
            return response

        match = resolve(request.path)
        logging.info(match)

        # se omite esta regla al mostrar imagen de paradero
        if match.url_name == 'paradero_imagen-detail' and request.method == 'GET':
            response = self.get_response(request)
            return response

        if match.url_name == 'auth_login' and request.method == 'POST':
            response = self.get_response(request)
            return response

        if match.url_name == 'auth_recuperar':
            response = self.get_response(request)
            return response

        if match.url_name == 'auth_info':
            response = self.get_response(request)
            return response

        if match.url_name == 'auth_contrasena':
            response = self.get_response(request)
            return response

        # se omite esta regla al mostrar informacion publica de paradero
        if match.url_name == 'paradero-info-public' and request.method == 'GET':
            response = self.get_response(request)
            return response

        if not request.headers.get('Authorization'):
            return HttpResponse('Debe indicar el token de autorización', status = 400)

        authorization = request.headers.get('Authorization').split(' ')
        token = authorization[1]

        try:
            decoded = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
        except jwt.ExpiredSignatureError:
            return HttpResponse('token ya no es valido', status = 400)
        except jwt.InvalidTokenError:
            return HttpResponse('token es invalido', status = 400)

        if decoded['login'] != '0':
            usuario = Usuario.objects.filter(login = decoded['login'], vigente = True).values().first()
            if not usuario:
                return HttpResponse('Usuario ya no vigente', status = 400)

            persona = Persona.objects.filter(rut = usuario['rut_id']).values().first()
            if not persona:
                return HttpResponse('No existe información de la persona', status = 500)

            request.jwt_info = { 'login': usuario['login'], 'persona': persona }
        else:
            request.jwt_info = { 'login': '0', 'persona': None }

        response = self.get_response(request)
        return response
