from django.conf import settings
from django.contrib.auth import logout
from django.urls import reverse
from django.utils.decorators import method_decorator
from django.views.decorators.debug import sensitive_post_parameters
from registration.backends.simple.views import RegistrationView
from cart.models import ChosenReward
from purist.models import AccountType
from .forms import CartRegistrationFormWithCaptcha, CartRegistrationForm
from limitmonitor.common import forced_update
from limitmonitor.subscription import SubscriptionManager, SubscriptionStatus
import json
import logging

log = logging.getLogger(__name__)


class CartRegistrationView(RegistrationView):
    form_class = CartRegistrationFormWithCaptcha
    template_name = 'cart/registration_form.html'
    reward = layout = bundle = period = None

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

    def get_form_class(self):
        if settings.DEBUG_REMOVE_CAPTCHA:
            return CartRegistrationForm
        return self.form_class

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

        if self.layout == 'basic':
            is_billing = False
        context['is_billing'] = is_billing
        context['reg_opts'] = json.dumps(context['form'].reg_options)
        return context

    def get(self, *args, **kwargs):
        logout(self.request)
        self.layout = kwargs.get('layout', None)
        return super().get(*args, **kwargs)

    def post(self, *args, **kwargs):
        self.reward = kwargs.get('reward', None)
        self.layout = kwargs.get('layout', None)
        return super().post(*args, **kwargs)

    def get_success_url(self, user):

        if self.bundle == 'Basic':

            url = reverse('profile')

        else:
            # go to WooCommerce cart URL
            url = user.chosenreward.url

        return url

    def register(self, form):

        user = super().register(form)
        self.period = form.cleaned_data['period_choice']
        self.bundle = form.cleaned_data['bundle_choice']
        url = form.reg_options[self.bundle][self.period]['url']
        try:
            cart_n = int(url.split('/')[-2])
        except IndexError:
            cart_n = -1
        reg_url = '{}/{}/{}&reauth=1'.format(settings.WOO_URL,
                                             'wp-login.php?redirect_to=',
                                             url)
        reward = ChosenReward(user=user, reward=cart_n, url=reg_url)

        if self.bundle == 'Basic':
            user.account_type = AccountType.BASIC

            try:
                new_sub = SubscriptionManager.create_subscription(
                    user, paid=True,
                    status=SubscriptionStatus.ACTIVE,
                    billing_email=user.email
                )

                if new_sub is None:
                    raise Exception("Subscription is None.")

                forced_update(user)

            except Exception as e:
                message = "Failed to create subscription for basic user {}.".format(user)
                logging.exception(message)

        elif self.bundle == 'Complete':
            user.account_type = AccountType.COMPLETE

        if self.bundle == 'Family':
            user.account_type = AccountType.GROUP

        user.save()
        reward.save()
        return user

    @method_decorator(sensitive_post_parameters('password1', 'password2'))
    def dispatch(self, *args, **kwargs):
        return super().dispatch(*args, **kwargs)
