from django.template.loader import render_to_string
from django.contrib import messages
from django.views.generic import FormView

from ocyan.main.loading import get_baseclass
from ocyan.plugin.cookie_jar.contextprocessors import cookie_jar

from oscar.core.loading import get_class

BasketMessageGenerator = get_class("basket.utils", "BasketMessageGenerator")

BaseBasketAddView = get_baseclass(
    "basket.views",
    "BasketAddView",
    "ocyan.plugin.cookie_jar.cookiejar_basket_extension",
)


class BasketAddView(BaseBasketAddView):
    def __init__(self, *args, **kwargs):
        self.line = None
        self.line_created = None
        super().__init__(*args, **kwargs)

    def form_valid(self, form):
        offers_before = self.request.basket.applied_offers()

        self.line, self.line_created = self.request.basket.add_product(
            form.product, form.cleaned_data["quantity"], form.cleaned_options()
        )

        messages.success(
            self.request, self.get_success_message(form), extra_tags="safe noicon"
        )

        # Check for additional offer messages
        BasketMessageGenerator().apply_messages(self.request, offers_before)

        # Send signal for basket addition
        self.add_signal.send(
            sender=self,
            product=form.product,
            user=self.request.user,
            request=self.request,
        )

        # pylint: disable=E1003
        return super(FormView, self).form_valid(form)

    def get_success_message(self, form):
        return render_to_string(
            "oscar/basket/messages/addition.html",
            {
                "product": form.product,
                "quantity": form.cleaned_data["quantity"],
                "request": self.request,
                "line": self.line,
                **cookie_jar(self.request),
            },
        )
