import os
from django.conf import settings
from django.template import Context
from django.template.loader import get_template
from xhtml2pdf import pisa
from django.contrib.staticfiles import finders
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.http.response import HttpResponse
from django.views import View
from django.views.generic import ListView
from datetime import datetime
from django.core.mail import EmailMultiAlternatives

from autenticacion.models import perfil
from autenticacion.forms import Formperfil, FormperfilEnv
from universidad.models import carrera


# Create your views here. post.usuario = request.user


@login_required(login_url='/acceder')
def Perfil(request):
    id = request.user.id
    form = perfil.objects.get(usuario_id=id)
    user = User.objects.get(id=id)
    datos = carrera.objects.get(id=form.id_carrera_id)
    count = perfil.objects.filter(usuario_id=form.usuario_id).count()
    return render(request, 'perfil.html', {"form": form, "user": user, "datos": datos, "count": count})


@login_required(login_url='/acceder')
def ActualizarPerfil(request, id):
        data = request.user.password + str(request.user.id)
        key = ''.join(ch for ch in data if ch.isalnum())
        update = perfil.objects.values('key').filter(usuario_id=request.user.id).update(key=key)
        instance= get_object_or_404(perfil, pk=id)
        form = Formperfil(request.POST or None, instance=instance)
        context= {'form': form}
        if form.is_valid():
                obj= form.save(commit= False)
                obj.save()
                messages.success(request, "El perfil fue actualizado")
                return redirect("perfil")

        else:
                context= {'form': form, 'error': 'Error al actualizar'}
                return render(request,'actualizar_perfil.html' , context)


@login_required(login_url='/acceder')
def alta_perfil(request):
    if request.method == "POST":
        form = Formperfil(request.POST, request.FILES)
        if form.is_valid():
            post = form.save(commit=False)
            post.save()
            folio = form.cleaned_data.get("matricula")
            messages.success(request, f"El registro {folio} se ha creado o actualizado correctamente")
            return redirect("index")
        else:
            for field, items in form.errors.items():
                for item in items:
                    messages.error(request, '{}: {}'.format(field, item))
    user = request.user.id
    if perfil.objects.filter(usuario_id=user).exists():
        messages.success(request, f"El registro ya existe")
        return redirect("perfil")
    user = request.user
    data = user.password
    key = ''.join(ch for ch in data if ch.isalnum())
    form = FormperfilEnv()
    return render(request, "alta_perfil.html", {"form": form, "user": user, "key": key})


@login_required(login_url='/acceder')
def mail(request):
    if request.method == "POST":
        id = request.POST.get("id")
        form = perfil.objects.get(usuario_id=id)
        user = User.objects.get(id=id)
        subject = 'Codigo QR'
        template = get_template('email.html')
        content = template.render({
            'form': form,
        })
        message = EmailMultiAlternatives(subject, 
                                        '',
                                        settings.EMAIL_HOST_USER, 
                                        [user.email]) 

        message.attach_alternative(content, 'text/html')
        message.send()
        messages.success(request, f"El Correo con el codigo QR ha sido enviado")
        return redirect("perfil")
    else:
            for field, items in form.errors.items():
                for item in items:
                    messages.error(request, '{}: {}'.format(field, item))

        
 