from django.db import models
from django.utils.text import slugify
from wagtail import blocks
from wagtail.admin.panels import FieldPanel
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


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

    parent_page_types = ["course.CoursePage"]
    subpage_types = ["competence.CompetencePage"]

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

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

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


class CompetencePage(CourseBasePage):
    serialize_field_names = [
        "competence_id",
        "children",
    ]

    parent_page_types = ["competence.CompetenceProfilePage"]
    subpage_types = ["competence.PerformanceCriteria"]
    competence_id = models.TextField(default="A1")
    items = StreamField(
        [
            ("item", blocks.TextBlock()),
        ],
        use_json_field=True,
    )

    content_panels = [
        FieldPanel("title"),
        FieldPanel("competence_id"),
    ]

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


class PerformanceCriteria(CourseBasePage):
    parent_page_types = ["competence.CompetenceProfilePage"]
    competence_id = models.TextField(default="A1.1")
    learning_unit = models.ForeignKey(
        "learnpath.LearningUnit",
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
    )

    content_panels = [
        FieldPanel("title"),
        FieldPanel("competence_id"),
        FieldPanel("learning_unit"),
    ]

    def save(self, clean=True, user=None, log_action=False, **kwargs):
        profile_parent = self.get_ancestors().exact_type(CompetenceProfilePage).last()
        if self.learning_unit and self.learning_unit.course_category:
            self.slug = find_available_slug(
                slugify(
                    f"{profile_parent.slug}-crit-{self.competence_id}-{self.learning_unit.course_category.title}",
                    allow_unicode=True,
                ),
                ignore_page_id=self.id,
            )
        else:
            self.slug = find_available_slug(
                slugify(
                    f"{profile_parent.slug}-crit-{self.competence_id}",
                    allow_unicode=True,
                ),
                ignore_page_id=self.id,
            )
        super(PerformanceCriteria, self).save(clean, user, log_action, **kwargs)

    @classmethod
    def get_serializer_class(cls):
        from vbv_lernwelt.competence.serializers import PerformanceCriteriaSerializer

        return PerformanceCriteriaSerializer

    def get_admin_display_title(self):
        if self.learning_unit and self.learning_unit.course_category:
            return f"{self.competence_id} ({self.learning_unit.course_category.title}) {self.draft_title[:30]}"
        else:
            return f"{self.competence_id} {self.draft_title[:30]}"
