from django.contrib import admin

from noita.services.objectives import parse_objectives_and_store
from .models import LogfileSubmission, Objectiv, ObjectivPoint, DeathCounter


@admin.register(LogfileSubmission)
class LogfileSubmissionAdmin(admin.ModelAdmin):
    list_display = (
        "id",
        "user",
        "content_type",
        "file_size",
        "created_at",
        "processed",
    )
    list_filter = ("content_type", "processed", "created_at")
    search_fields = ("id", "user__username")
    readonly_fields = ("id", "created_at", "updated_at")
    fieldsets = (
        ("Identification", {"fields": ("id",)}),
        ("File Information", {"fields": ("file", "content_type", "file_size")}),
        ("User", {"fields": ("user",)}),
        ("Timestamps", {"fields": ("created_at", "updated_at")}),
        ("Processing", {"fields": ("processed",)}),
    )

    actions = ["validate_submission"]

    def validate_submission(self, request, queryset):
        for logfile in queryset:
            parse_objectives_and_store(logfile)

        self.message_user(request, f"{queryset.count()} submissions validated.")


@admin.register(Objectiv)
class ObjectivAdmin(admin.ModelAdmin):
    list_display = ("objectiv_id", "user", "first_seen_at", "get_user_objectiv_count")
    list_filter = ("objectiv_id", "user")
    search_fields = ("objectiv_id", "user__username")
    readonly_fields = ("user", "first_seen_at")

    def get_user_objectiv_count(self, obj):
        return Objectiv.objects.filter(
            objectiv_id=obj.objectiv_id, user=obj.user
        ).count()

    get_user_objectiv_count.short_description = "Count"


@admin.register(ObjectivPoint)
class ObjectivPointAdmin(admin.ModelAdmin):
    list_display = ("objectiv_id", "display_string", "max_count", "point")
    list_filter = ("objectiv_id",)
    search_fields = ("objectiv_id", "display_string")
    fieldsets = (
        ("Objective Information", {"fields": ("objectiv_id", "display_string")}),
        ("Scoring", {"fields": ("max_count", "point")}),
    )


@admin.register(DeathCounter)
class DeathCounterAdmin(admin.ModelAdmin):
    list_display = ("user_id", "seed", "seen_at")
    list_filter = ("user_id", "seed")
    search_fields = ("user_id", "seed")

    fieldsets = (
        ("User Information", {"fields": ("user_id",)}),
        ("Scoring", {"fields": ("seed",)}),
    )
