from django.contrib import admin
from django.http import HttpRequest
from locations.models import GeoLocation
from scrobbles.admin import ScrobbleInline
from scrobbles.tasks import reverse_geocode_geolocation


@admin.register(GeoLocation)
class GeoLocationAdmin(admin.ModelAdmin):
    date_hierarchy = "created"
    list_display = (
        "created",
        "lat",
        "lon",
        "title",
        "altitude",
        "city",
        "state_province",
        "country",
    )
    ordering = ("-created",)
    search_fields = ("title",)
    actions = ["reverse_geocode_selected"]
    inlines = [
        ScrobbleInline,
    ]

    @admin.action(description="Reverse geocode selected locations")
    def reverse_geocode_selected(self, request: HttpRequest, queryset):
        enqueued = 0
        for location in queryset.filter(postal_code__isnull=True).iterator():
            reverse_geocode_geolocation.delay(location.id)
            enqueued += 1
        msg = f"Enqueued reverse geocoding for {enqueued} locations"
        self.message_user(request, msg)
