from ckeditor_uploader.widgets import CKEditorUploadingWidget
from taggit.models import Tag

from django import forms
from django.utils import timezone
from django.utils.dates import MONTHS
from django.utils.translation import gettext_lazy as _

from .models import Post, Event, News, FetMeeting


class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = [
            "title",
            "subtitle",
            "tags",
            "image",
            "body",
            "slug",
            "author",
            "public_date",
        ]

        widgets = {"body": CKEditorUploadingWidget(config_name="default")}

    class Media:
        js = (
            "js/auto_slug.js",  # automatic slag completion via ajax
            "js/tag_completion.js",  # to get a list for tag autocompletion via ajax
        )


class NewsForm(PostForm):
    class Meta:
        model = News
        fields = [
            "title",
            "subtitle",
            "tags",
            "status",
            "image",
            "body",
            "slug",
            "author",
            "public_date",
            "is_pinned",
        ]

        labels = {
            "title": _("Titel"),
            "subtitle": _("Untertitel"),
            "image": _("Hintergrundbild"),
            "body": _("Text"),
            "slug": _("Permalink"),
            "author": _("Autor"),
            "public_date": _("Veröffentlichung"),
            "is_pinned": _("Post anheften"),
        }

        help_texts = {
            "tags": _(
                "Die Hashtags ohne '#' eintragen, und mit Komma kann man mehrere Tags anfügen."
            ),
            "image": _("Verwendbare Formate: ..."),
            "is_pinned": _(
                "Dieser Post soll an die Startseite als erster Post angeheftet werden."
            ),
        }

        widgets = {"body": CKEditorUploadingWidget(config_name="default")}

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)  # to get the self.fields set
        self.fields["author"].queryset = self.fields["author"].queryset.order_by(
            "username"
        )


class EventForm(PostForm):
    class Meta:
        model = Event
        fields = [
            "title",
            "subtitle",
            "tags",
            "status",
            "image",
            "body",
            "event_start",
            "event_end",
            "event_place",
            "slug",
            "author",
            "public_date",
            "is_pinned",
        ]

        labels = {
            "title": _("Titel"),
            "subtitle": _("Untertitel"),
            "image": _("Hintergrundbild"),
            "body": _("Text"),
            "event_start": _("Start des Events"),
            "event_end": _("Ende des Events"),
            "event_place": _("Ort des Events"),
            "slug": _("Permalink"),
            "author": _("Autor"),
            "public_date": _("Veröffentlichung"),
            "is_pinned": _("Event anheften"),
        }

        help_texts = {
            "tags": _(
                "Die Hashtags ohne '#' eintragen, und mit Komma kann man mehrere Tags anfügen."
            ),
            "image": _("Verwendbare Formate: "),
            "is_pinned": _(
                "Dieses Event soll an die Startseite als erster Post angeheftet werden."
            ),
        }

        widgets = {"body": CKEditorUploadingWidget(config_name="default")}

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)  # to get the self.fields set
        self.fields["author"].queryset = self.fields["author"].queryset.order_by(
            "username"
        )

        self.fields["event_start"].required = True
        self.fields["event_end"].required = False

        if "event_place" in self.fields:
            self.fields["event_place"].required = True


class FetMeetingForm(PostForm):
    class Meta:
        model = FetMeeting
        fields = ["event_start", "event_end", "event_place", "tags"]

        labels = {
            "event_start": _("Start der Sitzung"),
            "event_end": _("Ende der Sitzung"),
            "event_place": _("Ort der Sitzung"),
        }

        help_texts = {
            "tags": _(
                "Die Hashtags ohne '#' eintragen, und mit Komma kann man mehrere Tags anfügen."
            ),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)  # to get the self.fields set

        self.fields["event_start"].required = True
        self.fields["event_end"].required = False

        tags = []
        tags.append(Tag())
        tags[0].name = "fachschaft"
        self.fields["tags"].initial = tags


class PostSearchForm(forms.Form):
    year_choices = [("", _("Alle"))]
    month_choices = [("", _("Alle"))] + list(MONTHS.items())

    year = forms.ChoiceField(label="Jahr", choices=year_choices, required=False)
    month = forms.ChoiceField(label="Monat", choices=month_choices, required=False)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)  # to get the self.fields set

        try:
            first_post = Post.objects.get_queryset().last()

            if first_post:
                year_of_first_post = first_post.public_date.year
                years = range(year_of_first_post, timezone.now().date().year + 1)
                year_choices = [("", _("Alle"))] + [(i, i) for i in years]
                self.fields["year"].choices = year_choices

        except:
            pass
