import taggit.admin

from django.contrib import admin, auth
from django.contrib.flatpages.admin import FlatPageAdmin
from django.contrib.flatpages.models import FlatPage
from django.contrib.sites.models import Site
from django.utils.translation import gettext_lazy as _

from .forms import FlatPageForm
from .models import CustomFlatPage


# Define a new FlatPageAdmin
class CustomFlatPageAdmin(FlatPageAdmin):
    form = FlatPageForm
    fieldsets = (
        (
            None,
            {
                "fields": (
                    "url",
                    "title",
                    "content",
                )
            },
        ),
        (
            _("Advanced options"),
            {
                "classes": ("collapse",),
                "fields": ("registration_required", "template_name"),
            },
        ),
    )
    list_display = ["url", "title", "registration_required"]
    list_filter = ("registration_required",)


# Set the ordering of models in Admin Dashboard
def get_app_list(self, request):
    """
    Return a sorted list of all the installed apps that have been
    registered in this site.
    """
    # Retrieve the original list
    app_dict = self._build_app_dict(request)
    app_list = sorted(app_dict.values(), key=lambda x: x["name"].lower())

    # Sort the models customably within each app.
    for app in app_list:
        if app["app_label"] == "intern":
            ordering = {
                "Themenbereiche": 1,
                "Themen": 2,
                "Anhang Ordner": 3,
                "Etherpads": 4,
                "Dateien": 5,
            }
            app["models"].sort(key=lambda x: ordering[x["name"]])

        elif app["app_label"] == "members":
            ordering = {
                "Mitglieder": 1,
                "Tätigkeitsbereiche": 2,
                "Tätigkeiten": 3,
            }
            app["models"].sort(key=lambda x: ordering[x["name"]])

        elif app["app_label"] == "posts":
            ordering = {
                "News": 1,
                "Events": 2,
                "Fet Sitzungen": 3,
            }
            app["models"].sort(key=lambda x: ordering[x["name"]])

    return app_list


admin.AdminSite.get_app_list = get_app_list

# Customise the Django Admin
admin.site.index_title = "FET"
admin.site.site_header = "Admin"
admin.site.site_title = "Admin"

# Re-register FlatPageAdmin
admin.site.unregister(FlatPage)
admin.site.register(CustomFlatPage, CustomFlatPageAdmin)

admin.site.unregister(Site)

admin.site.unregister(auth.models.User)
admin.site.unregister(auth.models.Group)
admin.site.unregister(taggit.models.Tag)
