import re

from django.db import models
from django.utils.text import slugify
from wagtail.admin.panels import FieldPanel
from wagtail.documents.models import AbstractDocument, Document
from wagtail.fields import RichTextField
from wagtail.models import Page

from vbv_lernwelt.core.constants import (
    DEFAULT_RICH_TEXT_FEATURES,
    DEFAULT_RICH_TEXT_FEATURES_WITH_HEADER,
)
from vbv_lernwelt.core.model_utils import find_available_slug
from vbv_lernwelt.course.models import CourseBasePage


class MediaLibraryPage(CourseBasePage):
    parent_page_types = ["course.CoursePage"]
    subpage_types = [
        "media_library.MediaLibraryCategoryPage",
        "media_library.MediaLibraryUrlPage",
    ]

    serialize_field_names = ["course", "description", "children"]

    description = RichTextField(blank=True, features=DEFAULT_RICH_TEXT_FEATURES)

    content_panels = [
        FieldPanel("title", classname="full title"),
        FieldPanel("description", classname="full title"),
    ]

    def save(self, clean=True, user=None, log_action=False, **kwargs):
        self.slug = find_available_slug(
            slugify(f"{self.get_parent().slug}-media", allow_unicode=True),
            ignore_page_id=self.id,
        )
        super(MediaLibraryPage, self).save(clean, user, log_action, **kwargs)

    def get_frontend_url(self):
        return f"/course/{self.slug.replace('-media', '')}/media"


class MediaLibraryCategoryPage(CourseBasePage):
    """
    Kategorie unter Mediathek: "Allgemeines" oder "Handlungsfelder"
    """

    parent_page_types = ["media_library.MediaLibraryPage"]
    subpage_types = ["media_library.MediaLibraryContentPage"]

    serialize_field_names = ["children", "icon_url", "description"]

    description = RichTextField(blank=True, features=DEFAULT_RICH_TEXT_FEATURES)
    icon_url = models.CharField(
        max_length=255, default="/static/icons/icon-handlungsfelder-overview.svg"
    )

    content_panels = [
        FieldPanel("title"),
        FieldPanel("icon_url"),
        FieldPanel("description"),
    ]

    def save(self, clean=True, user=None, log_action=False, **kwargs):
        self.slug = find_available_slug(
            slugify(f"{self.get_parent().slug}-cat-{self.title}", allow_unicode=True),
            ignore_page_id=self.id,
        )
        super(MediaLibraryCategoryPage, self).save(clean, user, log_action, **kwargs)

    def get_frontend_url(self):
        r = re.compile(r"^(?P<coursePart>.+?)-media-cat-(?P<catPart>.+)$")
        m = r.match(self.slug)
        return f"/course/{m.group('coursePart')}/media/{m.group('catPart')}"


class MediaLibraryContentPage(CourseBasePage):
    """
    Inhalt einer Seite in der Mediathek, entweder Handlungsfeld wie "Fahrzeug" oder
    Unterseite unter "Allgemein" wie "Versicherungswirtschaft"
    """

    parent_page_types = ["media_library.MediaLibraryCategoryPage"]

    serialize_field_names = [
        "icon_overview_url",
        "icon_detail_url",
        "description",
        "body",
    ]

    description = RichTextField(blank=True, features=DEFAULT_RICH_TEXT_FEATURES)
    icon_overview_url = models.CharField(
        max_length=255, default="/static/icons/handlungsfelder/icon-hf-fahrzeug.svg"
    )
    icon_detail_url = models.CharField(
        max_length=255,
        default="/static/icons/handlungsfelder/icon-hf-fahrzeug-detail.svg",
    )

    body = RichTextField(
        blank=True, features=DEFAULT_RICH_TEXT_FEATURES_WITH_HEADER + ["h2"]
    )

    content_panels = [
        FieldPanel("title"),
        FieldPanel("icon_overview_url"),
        FieldPanel("icon_detail_url"),
        FieldPanel("description"),
        FieldPanel("body"),
    ]

    def save(self, clean=True, user=None, log_action=False, **kwargs):
        self.slug = find_available_slug(
            slugify(
                f"{self.get_parent().slug}-content-{self.title}", allow_unicode=True
            ),
            ignore_page_id=self.id,
        )
        super(MediaLibraryContentPage, self).save(clean, user, log_action, **kwargs)

    def get_frontend_url(self):
        r = re.compile(
            r"^(?P<coursePart>.+?)-media-cat-(?P<catPart>.+?)-content-(?P<contentPart>.+)$"
        )
        m = r.match(self.slug)
        return f"/course/{m.group('coursePart')}/media/{m.group('catPart')}/{m.group('contentPart')}"


class MediaLibraryUrlPage(CourseBasePage):
    """
    Link in der Mediathek auf externe Seite, wie Lernmedien und/oder Lexikon
    """

    parent_page_types = ["media_library.MediaLibraryPage"]

    serialize_field_names = [
        "children",
        "icon_url",
        "content_url",
        "url_open_blank",
        "description",
        "body",
    ]

    description = RichTextField(blank=True, features=DEFAULT_RICH_TEXT_FEATURES)
    icon_url = models.CharField(
        max_length=255, default="/static/icons/icon-handlungsfelder-overview.svg"
    )
    content_url = models.URLField(blank=True)
    url_open_blank = models.BooleanField(default=False)
    body = RichTextField(
        blank=True,
        features=DEFAULT_RICH_TEXT_FEATURES_WITH_HEADER + ["h2"],
        help_text="Wird nur angezeigt, wenn kein Link angegeben ist.",
    )

    content_panels = [
        FieldPanel("title"),
        FieldPanel("icon_url"),
        FieldPanel("content_url"),
        FieldPanel("url_open_blank"),
        FieldPanel("description"),
        FieldPanel("body"),
    ]

    def save(self, clean=True, user=None, log_action=False, **kwargs):
        self.slug = find_available_slug(
            slugify(f"{self.get_parent().slug}-cat-{self.title}", allow_unicode=True),
            ignore_page_id=self.id,
        )
        super(MediaLibraryUrlPage, self).save(clean, user, log_action, **kwargs)

    def get_frontend_url(self):
        r = re.compile(r"^(?P<coursePart>.+?)-media-cat-(?P<catPart>.+)$")
        m = r.match(self.slug)
        return f"/course/{m.group('coursePart')}/media/{m.group('catPart')}"


class LibraryDocument(AbstractDocument):
    """Unused for now"""

    # Todo: check https://filepreviews.io/
    display_text = models.CharField(max_length=1024, default="")
    description = models.TextField(default="")
    link_display_text = models.CharField(max_length=1024, default="")
    thumbnail = models.CharField(default="", max_length=1024)

    admin_form_fields = Document.admin_form_fields + (
        "display_text",
        "description",
        "link_display_text",
        "thumbnail",
    )
