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("associationIndex")
class AssociationIndex(Page):
    max_count = 1
    subpage_types = ["associations.AssociationPage"]

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

    body = CommonStreamField

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

    graphql_fields = [
        GraphQLRichText("lead"),
        GraphQLStreamfield("body"),
    ]

    search_fields = Page.search_fields


class AssociationPage(Page):
    subpage_types = []
    parent_page_types = ["associations.AssociationIndex"]
    show_in_menus = False

    class AssociationType(models.TextChoices):
        FORENING = "forening", "Forening"
        UTVALG = "utvalg", "Utvalg"

    excerpt = models.TextField(max_length=512, blank=False)
    body = CommonStreamField
    association_type = models.CharField(
        max_length=64, choices=AssociationType, default=AssociationType.FORENING
    )
    logo = models.ForeignKey(
        "images.CustomImage",
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="+",
    )
    website_url = models.URLField()

    content_panels = Page.content_panels + [
        FieldPanel(
            "excerpt",
            heading="Utdrag",
            help_text="En veldig kort oppsummering av innholdet nedenfor. Brukes i listevisninger.",
        ),
        FieldPanel("body"),
        FieldPanel("logo"),
        FieldPanel("association_type", heading="Type"),
        FieldPanel("website_url", heading="Nettside"),
    ]

    graphql_fields = [
        GraphQLString("excerpt"),
        GraphQLStreamfield("body"),
        GraphQLImage("logo"),
        GraphQLString("website_url"),
        GraphQLString("association_type"),
    ]

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