from grapple.helpers import register_singular_query_field, register_streamfield_block
from grapple.models import GraphQLImage, GraphQLRichText, GraphQLStreamfield, GraphQLString
from wagtail import blocks
from wagtail.admin.panels import (
    FieldPanel,
)
from wagtail.fields import RichTextField, StreamField
from wagtail.images.blocks import ImageChooserBlock
from wagtail.models import Page
from wagtail.search import index
from wagtail_headless_preview.models import HeadlessMixin

from dnscms.blocks import BASE_BLOCKS


@register_streamfield_block
class SponsorBlock(blocks.StructBlock):
    name = blocks.CharBlock(max_length=255, label="Navn")
    logo = ImageChooserBlock(required=False, label="Logo")
    website = blocks.URLBlock(required=False, label="Nettside")
    text = blocks.RichTextBlock(
        features=["bold", "italic", "link", "ul", "ol"], required=False, label="Beskrivelse"
    )

    graphql_fields = [
        GraphQLString("name", required=False),
        GraphQLImage("logo", required=False),
        GraphQLString("website", required=False),
        GraphQLString("text", required=False),
    ]

    class Meta:
        label = "Sponsor"
        icon = "tag"


@register_singular_query_field("sponsorsPage")
class SponsorsPage(HeadlessMixin, Page):
    max_count = 1
    subpage_types = []

    lead = RichTextField(features=["italic", "link"], blank=True)
    sponsors = StreamField(
        [
            ("sponsor", SponsorBlock()),
        ],
        blank=True,
    )
    body = StreamField(BASE_BLOCKS)

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

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

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