from django.db import models
from django.utils.translation import gettext_lazy as _
from wagtail.admin.edit_handlers import (
    FieldPanel,
    FieldRowPanel,
    MultiFieldPanel,
    StreamFieldPanel,
)
from wagtail.core import blocks
from wagtail.core.fields import StreamField
from wagtail.core.models import Page
from wagtail.images.edit_handlers import ImageChooserPanel
from wagtail.snippets.blocks import SnippetChooserBlock
from wagtail.snippets.models import register_snippet

from kfet.cms.context_processors import get_articles


@register_snippet
class MemberTeam(models.Model):
    first_name = models.CharField(
        verbose_name=_("Prénom"), blank=True, default="", max_length=255
    )
    last_name = models.CharField(
        verbose_name=_("Nom"), blank=True, default="", max_length=255
    )
    nick_name = models.CharField(
        verbose_name=_("Alias"), blank=True, default="", max_length=255
    )
    photo = models.ForeignKey(
        "wagtailimages.Image",
        verbose_name=_("Photo"),
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="+",
    )

    class Meta:
        verbose_name = _("K-Fêt-eux-se")

    panels = [
        FieldPanel("first_name"),
        FieldPanel("last_name"),
        FieldPanel("nick_name"),
        ImageChooserPanel("photo"),
    ]

    def __str__(self):
        return self.get_full_name()

    def get_full_name(self):
        return "{} {}".format(self.first_name, self.last_name).strip()


class MenuBlock(blocks.StaticBlock):
    class Meta:
        icon = "list-ul"
        label = _("Carte")
        template = "kfetcms/block_menu.html"

    def get_context(self, *args, **kwargs):
        context = super().get_context(*args, **kwargs)
        context.update(get_articles())
        return context


class GroupTeamBlock(blocks.StructBlock):
    show_only = blocks.IntegerBlock(
        label=_("Montrer seulement"),
        required=False,
        help_text=_(
            "Nombre initial de membres affichés. Laisser vide pour tou-te-s "
            "les afficher."
        ),
    )
    members = blocks.ListBlock(
        SnippetChooserBlock(MemberTeam),
        label=_("K-Fêt-eux-ses"),
        classname="team-group",
    )

    class Meta:
        icon = "group"
        label = _("Groupe de K-Fêt-eux-ses")
        template = "kfetcms/block_teamgroup.html"


class ChoicesStreamBlock(blocks.StreamBlock):
    rich = blocks.RichTextBlock(label=_("Éditeur"))
    carte = MenuBlock()
    group_team = GroupTeamBlock()


class KFetStreamBlock(ChoicesStreamBlock):
    group = ChoicesStreamBlock(label=_("Contenu groupé"))


class KFetPage(Page):

    content = StreamField(KFetStreamBlock, verbose_name=_("Contenu"))

    # Layout fields

    TEMPLATE_COL_1 = "kfet/base_col_1.html"
    TEMPLATE_COL_2 = "kfet/base_col_2.html"
    TEMPLATE_COL_MULT = "kfet/base_col_mult.html"

    no_header = models.BooleanField(
        verbose_name=_("Sans en-tête"),
        default=False,
        help_text=_("Coché, l'en-tête (avec le titre) de la page n'est pas affiché."),
    )
    layout = models.CharField(
        verbose_name=_("Template"),
        choices=[
            (TEMPLATE_COL_1, _("Une colonne : centrée sur la page")),
            (TEMPLATE_COL_2, _("Deux colonnes : fixe à gauche, contenu à droite")),
            (TEMPLATE_COL_MULT, _("Contenu scindé sur plusieurs colonnes")),
        ],
        default=TEMPLATE_COL_MULT,
        max_length=255,
        help_text=_("Comment cette page devrait être affichée ?"),
    )
    main_size = models.CharField(
        verbose_name=_("Taille de la colonne de contenu"), blank=True, max_length=255
    )
    col_count = models.CharField(
        verbose_name=_("Nombre de colonnes"),
        blank=True,
        max_length=255,
        help_text=_(
            "S'applique au page dont le contenu est scindé sur plusieurs colonnes."
        ),
    )

    # Panels

    content_panels = Page.content_panels + [StreamFieldPanel("content")]

    layout_panel = [
        FieldPanel("no_header"),
        FieldPanel("layout"),
        FieldRowPanel([FieldPanel("main_size"), FieldPanel("col_count")]),
    ]

    settings_panels = [
        MultiFieldPanel(layout_panel, _("Affichage"))
    ] + Page.settings_panels

    # Base template
    template = "kfetcms/base.html"

    class Meta:
        verbose_name = _("page K-Fêt")
        verbose_name_plural = _("pages K-Fêt")

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

        page = context["page"]

        if not page.seo_title:
            page.seo_title = page.title

        return context
