from django.utils.translation import gettext as _
from wagtail import blocks
from ocyan.plugin.coyote.blocks.partials import CoyoteStructBlock
from ocyan.main.loading import get_baseclass

BaseHomePageContentStreamBlock = get_baseclass(
    "coyote.stream_blocks",
    "HomePageContentStreamBlock",
    "ocyan.plugin.wagtail_blog.wagtail_blog_coyote_extension",
)


class CoyoteBlogsBlock(CoyoteStructBlock):
    body = blocks.RichTextBlock(required=False, label=_("Short text"))
    blog_pages = blocks.PageChooserBlock(
        required=True,
        label=_("Blog overview page"),
        help_text=_(
            "Only add a blog overview page, if you don't there will be no blog items"
        ),
    )
    read_more = blocks.CharBlock(
        required=False, label=_("Read more text"), default=_("Read more")
    )
    read_more_button = blocks.CharBlock(
        required=False, label=_("Read more button"), default=_("More articles")
    )

    def get_context(self, value, parent_context=None):
        ctx = super().get_context(value, parent_context=parent_context)
        ctx["blog_items"] = (
            value["blog_pages"]
            .get_specific()
            .get_children()
            .live()
            .order_by("-last_published_at")[:3]
        )
        return ctx

    class Meta:
        template = "coyote/blocks/content/blogs.html"


class HomePageContentStreamBlock(BaseHomePageContentStreamBlock):
    blogs = CoyoteBlogsBlock(icon="pick")
