from django.apps import apps

from discgolf.models import DiscGolfCourse

from scrobbles.views import (
    ScrobbleableListView,
    ScrobbleableDetailView,
    ChartContextMixin,
)


class DiscGolfCourseListView(ScrobbleableListView):
    model = DiscGolfCourse


class DiscGolfCourseDetailView(ScrobbleableDetailView, ChartContextMixin):
    model = DiscGolfCourse

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        Scrobble = apps.get_model("scrobbles", "Scrobble")
        context["trail_gpx_url"] = None
        latest = (
            Scrobble.objects.filter(
                trail=self.object.trail, gpx_file__isnull=False
            )
            .order_by("-timestamp")
            .first()
        )
        if latest and latest.gpx_file:
            context["trail_gpx_url"] = latest.gpx_file.url
        return context
