from django.db import models
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
from wagtail.search import index

from dnscms.fields import CommonStreamField


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

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

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

    graphql_fields = [
        GraphQLRichText("lead"),
    ]

    search_fields = []


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

    excerpt = models.TextField(max_length=512, blank=False)
    lead = RichTextField(features=["bold", "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=(
            "Velg et bilde til bruk i på forsiden og andre visningsflater. "
            "Bør være et bilde eller en illustrasjon uten tekst."
        ),
    )

    content_panels = Page.content_panels + [
        FieldPanel(
            "excerpt",
            heading="Utdrag",
            help_text="En veldig kort oppsummering av innholdet i artikkelen. Brukes på forsiden og i artikkeloversikten.",
        ),
        FieldPanel("featured_image"),
        FieldPanel(
            "lead",
            heading="Ingress",
            help_text="Et kortfattet, innledende avsnitt som oppsummerer hovedinnholdet i artikkelen.",
        ),
        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"),
    ]
