import logging

from django.db import models
from wagtail.admin.edit_handlers import FieldPanel, TabbedInterface, ObjectList

from core.wagtail_utils import StrictHierarchyPage
from users.models import SchoolClass

logger = logging.getLogger(__name__)


class Chapter(StrictHierarchyPage):
    class Meta:
        verbose_name = 'Kapitel'
        verbose_name_plural = 'Kapitel'

    description = models.TextField(blank=True)

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

    settings_panels = [
        FieldPanel('slug')
    ]

    edit_handler = TabbedInterface([
        ObjectList(content_panels, heading='Content'),
        ObjectList(settings_panels, heading='Settings'),
    ])

    template = 'generic_page.html'

    parent_page_types = ['books.Module']
    subpage_types = ['books.ContentBlock']

    title_hidden_for = models.ManyToManyField(SchoolClass, related_name='hidden_chapter_titles')
    description_hidden_for = models.ManyToManyField(SchoolClass, related_name='hidden_chapter_descriptions')

    def sync_title_visibility(self, school_class_template, school_class_to_sync):
        if self.title_hidden_for.filter(id=school_class_template.id).exists() \
            and not self.title_hidden_for.filter(id=school_class_to_sync.id).exists():
            self.title_hidden_for.add(school_class_to_sync)

        if self.title_hidden_for.filter(
            id=school_class_to_sync.id).exists() \
            and not self.title_hidden_for.filter(id=school_class_template.id).exists():
            self.title_hidden_for.remove(school_class_to_sync)

    def sync_description_visibility(self, school_class_template, school_class_to_sync):
        if self.description_hidden_for.filter(id=school_class_template.id).exists() \
            and not self.description_hidden_for.filter(id=school_class_to_sync.id).exists():
            self.description_hidden_for.add(school_class_to_sync)

        if self.description_hidden_for.filter(
            id=school_class_to_sync.id).exists() \
            and not self.description_hidden_for.filter(id=school_class_template.id).exists():
            self.description_hidden_for.remove(school_class_to_sync)
