from django.urls import reverse_lazy
from django.views.generic import CreateView
from django.shortcuts import get_object_or_404
from django.contrib import messages

from reymotausers.forms import ReyMotaUserCreationForm
from accounts.models import InvitationCode


class SignUpView(CreateView):
    form_class = ReyMotaUserCreationForm
    success_url = reverse_lazy("login")
    template_name = "registration/signup.html"

    def get_initial(self):
        initial = super().get_initial()
        code = self.request.GET.get('code')
        if code:
            initial['invitation_code'] = code
        return initial

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        code = self.request.GET.get('code')
        if code:
            try:
                invitation = get_object_or_404(InvitationCode, code=code)
                if invitation.is_used:
                    messages.warning(self.request, 'Este código ya ha sido utilizado.')
                    context['invitation_valid'] = False
                elif not invitation.is_valid():
                    messages.warning(self.request, 'El código ha expirado.')
                    context['invitation_valid'] = False
                else:
                    context['invitation_valid'] = True
            except Exception:
                context['invitation_valid'] = False
                messages.error(self.request, 'El código no es válido.')
        else:
            context['invitation_valid'] = False
            messages.error(self.request, 'Se requiere un código de invitación.')
        return context