from django.shortcuts import render
from django.core.mail import send_mail
from django.urls import reverse_lazy, reverse
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponseRedirect
from django.views.generic import View, CreateView
from django.views.generic.edit import FormView
from .forms import UserRegisterForm, LoginForm, UpdatePasswordForm, VerificationForm
from .models import User
#functions
from .functions import code_generator

# Create your views here.

class UserRegisterView(FormView):
    template_name = 'users/register.html' #el template de la vista
    form_class = UserRegisterForm #formulario creado en el forms.py
    success_url = '/' #el succes_url lo que hace es redirigir una vez se ejecuta con exito en este caso el registro de un usuario en el template
    
    #función para validar los campos del formulario
    def form_valid(self, form):
        #
        #genera el codigo
        codigo = code_generator()

        
        User.objects.create_user(
            form.cleaned_data['username'],
            form.cleaned_data['email'],
            form.cleaned_data['password1'],
            nombres=form.cleaned_data['nombres'],
            apellidos=form.cleaned_data['apellidos'],
            genero=form.cleaned_data['genero'],
            codregistro=codigo #nuevo attr del modelo q asigna el codigo
        )
        #enviar el codigo
        asunto = 'Confirmacion de email'
        mensaje = 'Codigo de verificacion'
        email_remitente = 'caribedigital1@gmail.com'
        #llamo la función send_mail
        send_mail(asunto, mensaje,email_remitente, [ form.cleaned_data['email'],])
        #redirigir a pantalla de validación
        return HttpResponseRedirect(
            reverse(
                'users_app:user-verification'
            )
        )

class LoginUser(FormView):
    template_name = 'users/login.html'
    form_class = LoginForm
    success_url = reverse_lazy('home_app:panel')
    #funcion verificación
    def form_valid(self, form):
        user = authenticate(#esta función verifica que 1 usuario existe en la db
            username=form.cleaned_data['username'],
            password=form.cleaned_data['password']
        )#funcion login
        login(self.request, user)

        return super(LoginUser, self).form_valid(form)

class LogoutView(View):

    def get(self, request, *args, **kargs):
        logout(request)
        return HttpResponseRedirect(
            reverse(
                'users_app:user-login'
            )
        )


class UpdatePasswordView(LoginRequiredMixin, FormView):
    template_name = 'users/update.html'
    form_class = UpdatePasswordForm
    success_url = reverse_lazy('users_app:user-login')
    login_url = reverse_lazy('users_app:user-login')
    #funcion verificación
    def form_valid(self, form):
        usuario = self.request.user
        user = authenticate(
            username=usuario.username,
            password=form.cleaned_data['password1']
        )
        if user:
            new_password = form.cleaned_data['password2']
            usuario.set_password(new_password)
            usuario.save()
        
        logout(self.request)
        return super(UpdatePasswordView, self).form_valid(form)


class CodeVerificationView(FormView):
    template_name = 'users/verification.html'
    form_class = VerificationForm
    success_url = reverse_lazy('home_app:user-login')
    #funcion verificación
    def form_valid(self, form):
        #
        return super(CodeVerificationView, self).form_valid(form)

