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, StreamField
from wagtail.models import Page
from wagtail.search import index
from wagtail_headless_preview.models import HeadlessMixin

from dnscms.blocks import BASE_BLOCKS, PageSectionBlock
from dnscms.options import ALL_PIGS


@register_singular_query_field("studioPage")
class StudioPage(HeadlessMixin, Page):
    max_count = 1
    subpage_types = []
    show_in_menus = True

    logo = models.ForeignKey(
        "images.CustomImage",
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="+",
    )
    lead = RichTextField(features=["link"], blank=True)
    body = StreamField(BASE_BLOCKS + [("page_section", PageSectionBlock())])

    PIG_CHOICES = [
        ("", "Ingen"),
    ] + ALL_PIGS

    pig = models.CharField(
        max_length=32,
        choices=PIG_CHOICES,
        default="",
        blank=True,
        help_text="Grisen nedi hjørnet.",
    )

    content_panels = Page.content_panels + [
        FieldPanel("logo"),
        FieldPanel("lead", heading="Ingress"),
        FieldPanel("body", heading="Innhold"),
        FieldPanel("pig", heading="Gris"),
    ]

    graphql_fields = [
        GraphQLImage("logo"),
        GraphQLRichText("lead"),
        GraphQLStreamfield("body"),
        GraphQLString("pig", required=True),
    ]

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