from wagtail import blocks

from oscar.core.loading import get_model

from .blocks import RoadrunnerCategoryChooserBlock

Product = get_model("catalogue", "Product")


# Because we moved oscar related blocks to this plugin,
# we had to maintain backwards compatibility, eg;
# not suddenly losing blocks from a page. This only works if
# the class name of the block is the same. But in blocks.py
# there already is a CategoryChooserBlock for something else and this is
# why there's a category_block.py.
class CategoryChooserBlock(blocks.StructBlock):
    category = RoadrunnerCategoryChooserBlock(required=True)

    def get_context(self, value, parent_context=None):
        context = super().get_context(value, parent_context=parent_context)
        if value["category"]:
            products = (
                Product.objects.browsable()
                .filter(categories__in=[value["category"]])
                .distinct()
                .order_by("-priority", "title")
            )
            context["products"] = products
        else:
            context["products"] = Product.objects.none()
            warning = f"CategoryChooserBlock name={self.name}, definition_prefix={self.definition_prefix} is missing the category"
            page = parent_context.get("page", None)
            if page is not None:
                warning += f" on page {page} (pk={page.pk})"
        return context

    class Meta:
        template = "roadrunner_bs4/blocks/category_block.html"
        icon = "grip"
        label = "Category"
        group = "Webshop"
        preview = ["category"]
