from django.utils.translation import gettext as _

from wagtail import blocks

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

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_blog_items_queryset(self, value):
        blog_overview_page = value["blog_pages"].get_specific()
        if hasattr(blog_overview_page, "get_blog_queryset"):
            return blog_overview_page.get_blog_queryset()

        from ocyan.plugin.wagtail_blog.models import BlogPage

        queryset = BlogPage.objects.child_of(blog_overview_page).live()
        locale_id = getattr(blog_overview_page, "locale_id", None)
        if locale_id:
            queryset = queryset.filter(locale_id=locale_id)
        return queryset.order_by("-post_date")

    def get_context(self, value, parent_context=None):
        ctx = super().get_context(value, parent_context=parent_context)
        ctx["blog_items"] = self.get_blog_items_queryset(value)[:3]
        return ctx

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


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