# -*- coding: utf-8 -*-
import datetime

from django.db import models
from django.core.paginator import Paginator
from wagtail import blocks
from wagtail.images import get_image_model_string
from wagtail.search import index
from wagtail.fields import StreamField, RichTextField
from wagtail.images.blocks import ImageChooserBlock
from ocyan.plugin.wagtail.blocks import WrappedCharBlock
from ocyan.plugin.wagtail.models import AbstractBasePage
from ocyan.core.fender import config
from wagtail.admin.panels import FieldPanel, MultiFieldPanel

from django.utils.translation import gettext_lazy as _

# pylint: disable=E1101, E0401
try:
    from rr.edit_handlers import RoadRunnerPanel
    from rr.fields import RoadRunnerField
except ImportError:  # pragma: no cover - legacy fallback
    from roadrunner.edit_handlers import RoadRunnerPanel
    from roadrunner.fields import RoadRunnerField


class BlogPageList(AbstractBasePage):
    subpage_types = [
        "ocyan_plugin_wagtail_blog.BlogPage",
        "ocyan_plugin_wagtail_blog.PageMakerBlogPage",
    ]
    template = "blog/blog_list.html"

    def get_context(self, request, *args, **kwargs):
        context = super().get_context(request, *args, **kwargs)
        blogs = BlogPage.objects.child_of(self).live().order_by("-post_date")
        items_per_page = config.get("wagtail_blog", "items_per_page", 10)

        current_page = int(request.GET.get("p", 1))
        paginator = Paginator(blogs, items_per_page)
        page = paginator.page(current_page)

        context["page"] = self
        context["bloglist"] = self.get_siblings()
        context["blogs"] = blogs
        context["pages"] = page.object_list
        context["current_page"] = current_page
        context["last_page"] = paginator.num_pages
        context["paginator"] = paginator

        return context

    class Meta:
        verbose_name = _("Blog list")
        verbose_name_plural = _("Blog lists")


class BlogPage(AbstractBasePage):
    parent_page_types = [BlogPageList]
    subpage_types = []
    template = "blog/blog_item.html"

    post_date = models.DateField(default=datetime.date.today)
    intro = RichTextField()
    lead_image = models.ForeignKey(
        get_image_model_string(), on_delete=models.PROTECT, related_name="+"
    )
    magento_id = models.IntegerField(verbose_name="Magento Id", null=True, blank=True)

    body = StreamField(
        [
            ("heading", WrappedCharBlock(classname="full title", tag="h1")),
            ("paragraph", blocks.RichTextBlock()),
            ("image", ImageChooserBlock(template="blog/blog_image.html")),
        ]
    )

    content_panels = AbstractBasePage.content_panels + [
        MultiFieldPanel(
            [FieldPanel("post_date")], heading="Publicatie Datum (standaard op vandaag)"
        ),
        MultiFieldPanel(
            [
                FieldPanel("lead_image"),
                FieldPanel("intro"),
                FieldPanel("body"),
            ],
            heading="Content",
        ),
    ]

    search_fields = AbstractBasePage.search_fields + [
        index.SearchField("post_date"),
        index.SearchField("intro"),
        index.SearchField("body"),
    ]

    def get_context(self, request, *args, **kwargs):
        context = super().get_context(request, *args, **kwargs)
        recent_blog_posts = (
            BlogPage.objects.child_of(self.get_parent())
            .live()
            .order_by("-post_date")
            .exclude(pk=self.pk)[:4]
        )
        context["blogs"] = (
            BlogPage.objects.child_of(self.get_parent()).live().order_by("-post_date")
        )
        context["recent_blogs"] = recent_blog_posts
        return context

    def get_meta_image(self):
        if self.search_image:
            return self.search_image

        return self.lead_image

    class Meta:
        verbose_name = _("Blog entry")
        verbose_name_plural = _("Blog entries")


class PageMakerBlogPage(BlogPage):
    template = "roadrunner/roadrunner_page.html"

    content = RoadRunnerField(null=True, blank=True)

    content_panels = AbstractBasePage.content_panels + [
        MultiFieldPanel(
            [FieldPanel("post_date")], heading="Publicatie Datum (standaard op vandaag)"
        ),
        MultiFieldPanel(
            [
                FieldPanel("lead_image"),
                FieldPanel("intro"),
            ],
            heading="Summary content",
        ),
        RoadRunnerPanel("content"),
    ]
