from django.utils.translation import gettext as _
from wagtail import blocks

from ocyan.main.loading import get_ocyan_class, get_baseclass
from ocyan.plugin.coyote.blocks.partials import CoyoteStructBlock


BaseContactPageContentStreamBlock = get_baseclass(
    "coyote.stream_blocks",
    "ContactPageContentStreamBlock",
    "ocyan.plugin.contact_form.contact_form_coyote_extension",
)
ContactForm = get_ocyan_class("contact_form.forms", "ContactForm")


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

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

    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


class ContactPageContentStreamBlock(BaseContactPageContentStreamBlock):
    blogs = ContactFormBlock(icon="pick")
