from django.conf import settings
from django.contrib.auth import logout
from django.http import Http404
from django.urls import reverse

from invitation.models import Invitation
from registration.backends.simple.views import RegistrationView
from purist.models import AccountType
from cart.views import CartRegistrationFormWithCaptcha as \
    InvitationRegistrationForm
from limitmonitor.subscription import SubscriptionManager
from limitmonitor.common import forced_update


class InvitationRegistrationView(RegistrationView):
    form_class = InvitationRegistrationForm
    template_name = 'invitation/registration_form.html'
    msg_hash = None
    invitation = None

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['DEBUG_REGISTER_STATUS'] = settings.DEBUG_REGISTER_STATUS
        return context

    def get(self, *args, **kwargs):

        logout(self.request)

        self.msg_hash = kwargs.get('msg_hash', None)
        self.invitation = Invitation.objects.get_invitation_by_hash(
            self.msg_hash)
        inv = self.invitation

        if inv is None or not inv.validate(self.msg_hash):
            raise Http404('Invalid invitation')
        elif inv.consumed:
            raise Http404('Invitation already used')
        elif inv.expired():
            raise Http404('Invitation expired')
        elif len(inv.owner.invitation_set.filter(consumed=True)) >= 4:
            raise Http404('All memberships have been taken')
        return super().get(*args, **kwargs)

    def post(self, *args, **kwargs):

        self.msg_hash = kwargs.get('msg_hash', None)
        self.invitation = Invitation.objects.get_invitation_by_hash(
            self.msg_hash)
        return super().post(*args, **kwargs)

    def get_success_url(self, user):

        return reverse('profile')

    def register(self, form):

        # Create new user and set AccountType to INVITED
        user = super().register(form)
        user.account_type = AccountType.INVITED
        user.save()

        # set the invitation to consumed and link the guest user
        self.invitation.consumed = True
        self.invitation.guest = user
        self.invitation.save()

        # Create an Invitee subscritpion for the user
        sub = SubscriptionManager.create_invitee_subscription(user)
        if sub:
            forced_update(user)

        return user

    def get_form_kwargs(self):
        kwargs = super(InvitationRegistrationView, self).get_form_kwargs()
        kwargs['layout'] = 'Invitee'
        return kwargs
