# Django
from django.contrib import admin
from django.utils.translation import gettext as _

# Third party
from parler.admin import TranslatableAdmin

# Local application / specific library imports
from .forms import ApplicationAdminForm, CookieAdminForm
from .models import Application, Cookie, DailyConsentStats, Purpose


class CookieInline(admin.TabularInline):
    model = Cookie
    form = CookieAdminForm


@admin.register(Application)
class ApplicationAdmin(TranslatableAdmin):
    list_display = (
        "name",
        "cookies_number",
        "purposes_list",
        "camel_case_name",
        "is_active",
        "order",
    )
    list_editable = ("is_active", "order")
    form = ApplicationAdminForm
    inlines = [CookieInline]
    fieldsets = (
        (
            None,
            {
                "fields": (
                    "name",
                    "description",
                    "purposes",
                    "is_required",
                    "is_active",
                    "no_consent",
                    "slug",
                    "order",
                )
            },
        ),
    )

    @admin.display(description=_("Purposes"))
    def purposes_list(self, obj):
        return ", ".join([p.name for p in obj.purposes.all()])

    @admin.display(description=_("Cookies"))
    def cookies_number(self, obj):
        return obj.cookie_set.count()

    def get_prepopulated_fields(self, request, obj=None):
        # can't use `prepopulated_fields = ..` because it breaks the admin validation
        # for translated fields. This is the official django-parler workaround.
        return {"slug": ("name",)}


@admin.register(Purpose)
class PurposeAdmin(TranslatableAdmin):
    list_display = ("name", "order")
    list_editable = ("order",)


@admin.register(DailyConsentStats)
class DailyConsentStatsAdmin(admin.ModelAdmin):
    list_display = (
        "date",
        "accept_count",
        "decline_count",
        "save_count",
        "show_count",
        "no_interaction_count",
    )
    list_filter = ("date",)
    readonly_fields = (
        "date",
        "accept_count",
        "decline_count",
        "save_count",
        "show_count",
        "no_interaction_count",
    )

    def has_add_permission(self, request):
        return False
