from django.conf import settings

from oscar.apps.basket import views as oscar
from oscar.core.utils import redirect_to_referrer

from ocyan.core.utils import RequestCache


class BasketAddView(oscar.BasketAddView):
    def form_invalid(self, form):
        self.request.session["add_to_basket_form_errors"] = form.errors
        return redirect_to_referrer(self.request, "basket:summary")

    def get_success_url(self):
        if settings.SHOW_BASKET_POPUP_MODAL:
            success_url = super().get_success_url()
            product_pk = self.kwargs["pk"]
            self.request.session["added_product"] = product_pk
            self.request.session["added_quantity"] = self.quantity
            return "%s#prod_%s" % (success_url, product_pk)
        return super().get_success_url()

    def post(self, request, *args, **kwargs):
        if settings.SHOW_BASKET_POPUP_MODAL:
            self.quantity = request.POST.get("quantity", 1)  # pylint: disable=W0201
        return super().post(request, *args, **kwargs)


class BasketView(oscar.BasketView):
    def default_shipping_country(self):
        if self.request.user.is_authenticated:
            shipping_address = (
                self.request.user.addresses.filter(country__is_shipping_country=True)
                .order_by(
                    "-is_default_for_shipping",
                    "-num_orders_as_shipping_address",
                    "-date_created",
                )
                .first()
            )
            if shipping_address is not None:
                return shipping_address.country

        return None

    def formset_valid(self, formset):
        cache = RequestCache.cache_for_request(self.request)
        cache.clear()
        return super().formset_valid(formset)

    def setup(self, request, *args, **kwargs):
        super().setup(request, *args, **kwargs)

        country = self.default_shipping_country()
        if country is not None:
            self.request.META["shipping_country"] = country.pk
