from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import validate_email
from django.db import models
from django.utils.translation import gettext_lazy
from wagtail.admin.edit_handlers import (
    CommentPanel,
    FieldPanel,
    HelpPanel,
    MultiFieldPanel,
)
from wagtail.core.fields import RichTextField
from wagtail.core.models import Page
from wagtail.documents.edit_handlers import DocumentChooserPanel
from wagtail.images.edit_handlers import ImageChooserPanel
from wagtailmetadata.models import MetadataPageMixin

from shared.models import SubpageMixin
from shared.utils import subscribe_to_newsletter
from tuning import help
from uniweb.constants import RICH_TEXT_FEATURES


class CzechInspirationalHomePage(Page, MetadataPageMixin):
    ### FIELDS

    buy_book_url = models.URLField("URL pro nákup knihy", blank=True, null=True)

    # settings
    matomo_id = models.IntegerField(
        "Matomo ID pro sledování návštěvnosti", blank=True, null=True
    )

    ### PANELS

    content_panels = Page.content_panels + [
        FieldPanel("buy_book_url"),
    ]

    promote_panels = [
        MultiFieldPanel(
            [
                FieldPanel("seo_title"),
                FieldPanel("search_description"),
                ImageChooserPanel("search_image"),
                HelpPanel(help.build(help.IMPORTANT_TITLE)),
            ],
            gettext_lazy("Common page configuration"),
        ),
    ]

    settings_panels = [
        MultiFieldPanel(
            [
                FieldPanel("matomo_id"),
            ],
            "nastavení webu",
        ),
        CommentPanel(),
    ]

    ### RELATIONS

    subpage_types = [
        "czech_inspirational.CzechInspirationalChaptersPage",
        "czech_inspirational.CzechInspirationalDownloadPage",
    ]

    ### OTHERS

    class Meta:
        verbose_name = "Česko inspirativní"

    @property
    def root_page(self):
        return self

    @property
    def chapters_page_url(self):
        try:
            return (
                self.get_descendants()
                .type(CzechInspirationalChaptersPage)
                .live()
                .get()
                .get_url()
            )
        except Page.DoesNotExist:
            return "#"

    @property
    def download_page_url(self):
        try:
            return (
                self.get_descendants()
                .type(CzechInspirationalDownloadPage)
                .live()
                .get()
                .get_url()
            )
        except Page.DoesNotExist:
            return "#"

    def get_context(self, request):
        context = super().get_context(request)
        context["chapters"] = (
            self.get_descendants()
            .type(CzechInspirationalChapterPage)
            .live()
            .specific()
            .order_by("czechinspirationalchapterpage__number")
        )
        return context


class CzechInspirationalChaptersPage(Page, SubpageMixin, MetadataPageMixin):
    ### FIELDS

    ### PANELS

    promote_panels = [
        MultiFieldPanel(
            [
                FieldPanel("slug"),
                FieldPanel("seo_title"),
                FieldPanel("search_description"),
                ImageChooserPanel("search_image"),
                HelpPanel(help.build(help.NO_SEO_TITLE, help.NO_SEARCH_IMAGE)),
            ],
            gettext_lazy("Common page configuration"),
        ),
    ]

    settings_panels = [CommentPanel()]

    ### RELATIONS

    parent_page_types = ["czech_inspirational.CzechInspirationalHomePage"]
    subpage_types = ["czech_inspirational.CzechInspirationalChapterPage"]

    ### OTHERS

    class Meta:
        verbose_name = "Přehled kapitol"

    def get_context(self, request):
        context = super().get_context(request)
        context["chapters"] = (
            self.get_children()
            .live()
            .specific()
            .order_by("czechinspirationalchapterpage__number")
        )
        return context


class CzechInspirationalChapterPage(Page, SubpageMixin, MetadataPageMixin):
    ### FIELDS

    number = models.IntegerField("číslo kapitoly", default=0)
    text = RichTextField("text", blank=True, features=RICH_TEXT_FEATURES)
    extra_text = RichTextField(
        "extra modrý blok", blank=True, features=RICH_TEXT_FEATURES
    )
    author = models.CharField("autor", max_length=250, blank=True, null=True)
    image = models.ForeignKey(
        "wagtailimages.Image",
        on_delete=models.PROTECT,
        blank=True,
        null=True,
        verbose_name="obrázek",
    )

    ### PANELS

    content_panels = Page.content_panels + [
        FieldPanel("number"),
        FieldPanel("author"),
        ImageChooserPanel("image"),
        FieldPanel("text"),
        FieldPanel("extra_text"),
    ]

    promote_panels = [
        MultiFieldPanel(
            [
                FieldPanel("slug"),
                FieldPanel("seo_title"),
                FieldPanel("search_description"),
                ImageChooserPanel("search_image"),
                HelpPanel(help.build(help.NO_SEO_TITLE, help.NO_SEARCH_IMAGE)),
            ],
            gettext_lazy("Common page configuration"),
        ),
    ]

    settings_panels = [CommentPanel()]

    ### RELATIONS

    parent_page_types = ["czech_inspirational.CzechInspirationalChaptersPage"]
    subpage_types = []

    ### OTHERS

    class Meta:
        verbose_name = "Kapitola"

    def get_context(self, request):
        context = super().get_context(request)
        context["chapters"] = (
            self.get_siblings()
            .live()
            .specific()
            .order_by("czechinspirationalchapterpage__number")
        )
        return context


class CzechInspirationalDownloadPage(Page, SubpageMixin, MetadataPageMixin):
    ### FIELDS

    book_file = models.ForeignKey(
        "wagtaildocs.Document",
        verbose_name="ebook",
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="+",
    )

    ### PANELS

    content_panels = Page.content_panels + [
        DocumentChooserPanel("book_file"),
    ]

    promote_panels = [
        MultiFieldPanel(
            [
                FieldPanel("slug"),
                FieldPanel("seo_title"),
                FieldPanel("search_description"),
                ImageChooserPanel("search_image"),
                HelpPanel(help.build(help.NO_SEO_TITLE, help.NO_SEARCH_IMAGE)),
            ],
            gettext_lazy("Common page configuration"),
        ),
    ]

    settings_panels = [CommentPanel()]

    ### RELATIONS

    parent_page_types = ["czech_inspirational.CzechInspirationalHomePage"]
    subpage_types = []

    ### OTHERS

    class Meta:
        verbose_name = "Download"

    def get_context(self, request):
        context = super().get_context(request)

        if "stahnout" in request.GET:
            context["show"] = "download"
        elif "diky" in request.GET:
            context["show"] = "thanks"
        else:
            context["show"] = "info"

        if "email" in request.POST:
            context["show"] = "download"

            if "subscribe" in request.POST:
                email = request.POST.get("email", "")
                try:
                    validate_email(email)
                except ValidationError:
                    pass
                else:
                    subscribe_to_newsletter(
                        email,
                        settings.CZECH_INSPIRATIONAL_NEWSLETTER_ID,
                        settings.CZECH_INSPIRATIONAL_NEWSLETTER_SOURCE,
                    )

        return context