import re

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

from vbv_lernwelt.core.model_utils import find_available_slug
from vbv_lernwelt.course.models import CourseBasePage
from vbv_lernwelt.media_library.content_blocks import MediaContentCollection


class MediaLibraryPage(CourseBasePage):
    serialize_field_names = ["course", "children"]

    parent_page_types = ["course.CoursePage"]
    subpage_types = ["media_library.MediaCategoryPage"]

    content_panels = [
        FieldPanel("title", 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 MediaCategoryPage(CourseBasePage):
    """
    Handlungsfeld. zB. Fahrzeug
    """

    serialize_field_names = [
        "course_category",
        "introduction_text",
        "overview_icon",
        "detail_image",
        "description_title",
        "description_text",
        "items",
        "body",
    ]

    course_category = models.ForeignKey(
        "course.CourseCategory", on_delete=models.SET_NULL, null=True, blank=True
    )
    parent_page_types = ["media_library.MediaLibraryPage"]
    introduction_text = models.TextField(default="")
    description_title = models.TextField(
        default="Das erwartet dich in diesem Handlungsfeld"
    )
    description_text = models.TextField(default="")
    items = StreamField(
        [
            ("item", blocks.TextBlock()),
        ],
        use_json_field=True,
    )

    overview_icon = models.CharField(max_length=255, default="icon-hf-fahrzeug")
    detail_image = models.CharField(max_length=255, default="image-hf-fahrzeug")

    body = fields.StreamField(
        [("content_collection", MediaContentCollection())],
        use_json_field=True,
        null=True,
    )

    content_panels = [
        FieldPanel("title"),
        FieldPanel("course_category"),
        FieldPanel("introduction_text"),
        FieldPanel("description_title"),
        FieldPanel("description_text"),
        FieldPanel("items"),
        StreamFieldPanel("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(MediaCategoryPage, 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/category/{m.group('catPart')}"


class LibraryDocument(AbstractDocument):
    # Todo: check https://filepreviews.io/

    # Custom field example:
    display_text = models.CharField(max_length=1024, default="")
    description = models.TextField(default="")
    link_display_text = models.CharField(max_length=1024, default="")
    thumbnail = models.URLField()

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