from wagtail import blocks
from ocyan.main.loading import get_ocyan_class
from django.utils.translation import gettext_lazy as _


ContactForm = get_ocyan_class("contact_form.forms", "ContactForm")


class ContactFormBlock(blocks.StructBlock):
    title = blocks.CharBlock(blank=True, required=False, default="")

    class Meta:
        template = "contact_form/blocks/contact-form.html"
        icon = "form"
        help_text = _("A contact form has been added to this page!")
        label = _("Contact form")
        group = "Extra"

    def get_context(self, value, parent_context=None):
        context = super().get_context(value, parent_context=parent_context)
        request = context.get("request")
        post_data = request.session.pop("contact_form_post_data", None)
        form = ContactForm(post_data, request=request)
        if post_data is not None:
            form.is_valid()
        context["form"] = form
        return context
