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 wagtail_wordpress_import.models import WPImportedPageMixin

from dnscms.fields import CommonStreamField


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

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

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

    graphql_fields = [
        GraphQLRichText("lead"),
    ]

    search_fields = []


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

    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=(
            "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"),
    ]

    settings_panels = Page.settings_panels + WPImportedPageMixin.wordpress_panels

    def import_wordpress_data(self, data):
        import html

        from bs4 import BeautifulSoup

        def generate_excerpt(html_content):
            soup = BeautifulSoup(html_content, features="lxml")
            VALID_TAGS = ["div", "p"]

            for tag in soup.findAll("p"):
                if tag.name not in VALID_TAGS:
                    tag.remove()

            text = soup.get_text().strip()
            words = text.split(" ")
            if len(words) < 26:
                return text
            return " ".join(words[:25]) + " [...]"

        # Wagtail page model fields
        self.title = html.unescape(data["title"])
        self.slug = data["slug"]
        self.first_published_at = data["first_published_at"]
        self.last_published_at = data["last_published_at"]
        self.latest_revision_created_at = data["latest_revision_created_at"]
        self.search_description = data["search_description"]

        # debug fields
        self.wp_post_id = data["wp_post_id"]
        self.wp_post_type = data["wp_post_type"]
        self.wp_link = data["wp_link"]
        self.wp_raw_content = data["wp_raw_content"]
        self.wp_block_json = data["wp_block_json"]
        self.wp_processed_content = data["wp_processed_content"]
        self.wp_normalized_styles = data["wp_normalized_styles"]
        self.wp_post_meta = data["wp_post_meta"]

        # own model fields
        self.body = data["body"] or ""

        meta = data["wp_post_meta"]

        written_excerpt = meta.get("excerpt_encoded")
        generated_excerpt = ""
        if not written_excerpt:
            generated_excerpt = generate_excerpt(self.wp_processed_content)

        self.excerpt = written_excerpt or generated_excerpt or "[...]"
