from django.db import models
from django.utils.translation import gettext_lazy as _
from grapple.helpers import register_singular_query_field
from grapple.models import GraphQLImage, GraphQLRichText, GraphQLStreamfield, GraphQLString
from wagtail.admin.panels import FieldPanel
from wagtail.fields import RichTextField
from wagtail.models import Page, PageManager
from wagtail.search import index
from wagtail_headless_preview.models import HeadlessMixin

from dnscms.fields import CommonStreamField
from dnscms.wordpress.models import DeferWPFieldsManagerMixin, WPImportedPageMixin


class NewsPageManager(DeferWPFieldsManagerMixin, PageManager):
    pass


@register_singular_query_field("newsIndex")
class NewsIndex(HeadlessMixin, Page):
    max_count = 1
    subpage_types = ["news.NewsPage"]

    lead = RichTextField(features=["italic", "link"], blank=True)

    content_panels = Page.content_panels + [
        FieldPanel("lead", heading=_("Lead")),
    ]

    graphql_fields = [
        GraphQLRichText("lead"),
    ]

    search_fields = []

    class Meta:
        verbose_name = _("news index")
        verbose_name_plural = _("news indexes")


class NewsPage(HeadlessMixin, WPImportedPageMixin, Page):
    subpage_types = []
    parent_page_types = ["news.NewsIndex"]
    show_in_menus = False

    objects = NewsPageManager()

    excerpt = models.TextField(max_length=512, blank=False)
    lead = RichTextField(features=["italic", "link"], blank=True)
    body = CommonStreamField
    featured_image = models.ForeignKey(
        "images.CustomImage",
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="+",
        help_text=_(
            "Choose an image for use on the front page and other surfaces. "
            "Should be a photo or an illustration without too much text."
        ),
    )

    content_panels = Page.content_panels + [
        FieldPanel(
            "excerpt",
            heading=_("Excerpt"),
            help_text=_(
                "A very short summary of the article's content. "
                "Used on the front page and in the article listing."
            ),
        ),
        FieldPanel("featured_image"),
        FieldPanel(
            "lead",
            heading=_("Lead"),
            help_text=_(
                "A brief, introductory paragraph that summarizes the main content of the article."
            ),
        ),
        FieldPanel("body"),
    ]

    graphql_fields = [
        GraphQLString("excerpt"),
        GraphQLRichText("lead"),
        GraphQLStreamfield("body"),
        GraphQLImage("featured_image"),
    ]

    search_fields = Page.search_fields + [
        index.SearchField("excerpt", boost=1),
        index.SearchField("lead", boost=1),
        index.SearchField("body"),
    ]

    class Meta:
        verbose_name = _("news article")
        verbose_name_plural = _("news articles")
