from django.urls import reverse_lazy
from django.conf import settings
from django.views.generic.edit import FormView
from django.contrib.auth.mixins import LoginRequiredMixin
from .forms import ChooseBundleForm
from .models import BundleChange
from limitmonitor.common import active_subscription, can_change_bundle, \
    invitees_clean
from limitmonitor.models import get_available_bundles
from limitmonitor.subscription import BillingPeriod, SubscriptionStatus, \
    SubscriptionManager
from purist.models import AccountType


class UpgradeView(LoginRequiredMixin, FormView):

    template_name = 'bundlechange/upgrade.html'
    form_class = ChooseBundleForm
    success_url = reverse_lazy('upgrade')

    def get_form_kwargs(self):

        self.avl_bundles = get_available_bundles()
        self.sub = active_subscription(self.request.user)
        if self.sub:
            choices = self.sub.upgrade_choices(add_downgrade=True)
        else:
            choices = []

        kwargs = super(UpgradeView, self).get_form_kwargs()
        kwargs['choices'] = choices
        return kwargs

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

        form = super(UpgradeView, self).get_form(*args, **kwargs)
        form.user = self.request.user
        return form

    def get_context_data(self, **kwargs):

        context = super(UpgradeView, self).get_context_data(**kwargs)
        pending_changes = self.request.user.bundlechange_set.filter(
            is_pending=True
        )

        # sub = active_subscription(self.request.user)
        if self.sub is not None:
            context['current_bdl'] = (
                self.avl_bundles[str(self.sub.variation_id)]['short_title'])

        if len(pending_changes) > 0:
            context['has_pending_changes'] = True
            context['from_bdl'] = (
                self.avl_bundles[pending_changes[0].from_bdl]['short_title'])
            context['to_bdl'] = (
                self.avl_bundles[pending_changes[0].to_bdl]['short_title'])
            context['pay_url'] = pending_changes[0].pay_url
        else:
            context['has_pending_changes'] = False
        context['can_upgrade'] = can_change_bundle(self.request.user)
        context['invitees_clean'] = invitees_clean(self.request.user)
        return context

    def form_valid(self, form):

        variation_id = form.cleaned_data['bundle']
        acc_type = AccountType.from_str(
            self.avl_bundles[variation_id]['type']
        )
        period = BillingPeriod(self.avl_bundles[variation_id]['period'])

        if self.sub:
            new_sub = SubscriptionManager.create_subscription(
                self.request.user, account_type=acc_type,
                billing_period=period
            )
            pay_url = settings.WOO_UPGRADE_PAY_URL.format(new_sub.order_id,
                                                          new_sub.order_key)

            bundle_change = BundleChange(
                user=self.request.user,
                from_bdl=self.sub.variation_id,
                to_bdl=variation_id,
                is_pending=True,
                pay_url=pay_url,
                new_order_id=new_sub.order_id,
                old_subscription_id=self.sub.subscription_id
            )
            bundle_change.save()
            # Deactivate previous subscription
            self.sub.status = SubscriptionStatus.PENDING_CANCEL
            self.sub.save()

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