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 CompetenceNaviPage(CourseBasePage):
    parent_page_types = ["course.CoursePage"]
    subpage_types = ["competence.CompetenceCertificateList"]

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

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


class CompetenceCertificateList(CourseBasePage):
    """Kompetenznachweise für einen Lehrgang"""

    parent_page_types = ["competence.CompetenceNaviPage"]
    subpage_types = ["competence.CompetenceCertificate"]

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

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


class CompetenceCertificate(CourseBasePage):
    """einzelner Kompetenznachweis"""

    parent_page_types = ["competence.CompetenceCertificateList"]

    def __str__(self):
        course = self.get_course()
        return f"{course.title} - {self.title}"

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

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


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

    parent_page_types = ["competence.CompetenceNaviPage"]
    subpage_types = ["competence.ActionCompetence"]

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

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

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


class ActionCompetence(CourseBasePage):
    """Handlungskompetenz"""

    serialize_field_names = [
        "competence_id",
        "children",
    ]

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

    def get_frontend_url(self):
        return f""

    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(ActionCompetence, self).save(clean, user, log_action, **kwargs)


class PerformanceCriteria(CourseBasePage):
    """Leistungskriterium"""

    parent_page_types = ["competence.ActionCompetence"]
    competence_id = models.TextField(default="A1.1")
    learning_unit = models.ForeignKey(
        "learnpath.LearningUnit",
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
    )
    has_course_completion_status = models.BooleanField(default=True)
    can_user_self_toggle_course_completion = models.BooleanField(default=True)

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

    def get_frontend_url(self):
        return ""

    def save(self, clean=True, user=None, log_action=False, **kwargs):
        profile_parent = (
            self.get_ancestors().exact_type(ActionCompetenceListPage).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]}"
