from django.views import generic
from django.urls import reverse_lazy
from django.db.models import Count, Q

from people.models import Person, PersonScrobble


class PersonCreateUpdateView(generic.CreateView):
    model = Person
    fields = [
        "name",
        "bgstats_id",
        "boardgamearena_id",
        "bgg_username",
        "lichess_username",
        "bio",
    ]
    template_name = "people/person_form.html"
    success_url = reverse_lazy("people:person_form")

    def get_initial(self):
        initial = super().get_initial()
        initial["created_by"] = self.request.user
        return initial

    def get_context_data(self, **kwargs):
        context_data = super().get_context_data(**kwargs)
        context_data["people"] = (
            Person.objects.filter(created_by=self.request.user)
            .annotate(
                scrobble_count=Count(
                    "scrobble_associations",
                    filter=Q(scrobble_associations__user=self.request.user),
                )
            )
            .order_by("-scrobble_count", "name")
        )
        return context_data

    def form_valid(self, form):
        form.instance.created_by = self.request.user
        return super().form_valid(form)


class PersonUpdateView(generic.UpdateView):
    model = Person
    fields = [
        "name",
        "bgstats_id",
        "boardgamearena_id",
        "bgg_username",
        "lichess_username",
        "bio",
    ]
    template_name = "people/person_form.html"
    success_url = reverse_lazy("people:person_form")

    def get_context_data(self, **kwargs):
        context_data = super().get_context_data(**kwargs)
        context_data["people"] = (
            Person.objects.filter(created_by=self.request.user)
            .annotate(
                scrobble_count=Count(
                    "scrobble_associations",
                    filter=Q(scrobble_associations__user=self.request.user),
                )
            )
            .order_by("-scrobble_count", "name")
        )
        return context_data
