from django.db.models import Avg, Count, F
from django.views.generic import DetailView, ListView
from django.views.generic.list import MultipleObjectMixin

from .models import Developer, Game, GameSystem, Genre, Publisher

import logging

logger = logging.Logger(__name__)


class RecentGameList(ListView):
    model = Game
    paginate_by = 20
    queryset = Game.objects.order_by("-created")[:200]


class LibraryGameList(ListView):
    template_name = "games/game_library_list.html"
    model = Game
    paginate_by = 100

    def get_context_data(self, **kwargs):
        game_system_slug = self.request.GET.get("game_system")
        order_by = self.request.GET.get("order_by", "name")
        if order_by[0] == "-":
            order_by = order_by[1:]
            object_list = Game.objects.order_by(F(order_by).desc(nulls_last=True))
        else:
            object_list = Game.objects.order_by(F(order_by).asc(nulls_last=True))
        if game_system_slug:
            object_list = object_list.filter(
                game_system__retropie_slug=game_system_slug
            )
        context = super(LibraryGameList, self).get_context_data(
            object_list=object_list, **kwargs
        )
        return context


class FilterableBaseListView(ListView):
    VALID_ORDERING = ["name", "num_games", "rating"]

    def get_queryset(self, **kwargs):
        order_by = self.request.GET.get("order_by", "name")
        queryset = super().get_queryset(**kwargs)
        queryset = queryset.annotate(num_games=Count("game")).annotate(
            rating=Avg("game__rating")
        )
        if order_by.replace("-", "") not in self.VALID_ORDERING:
            logger.warning(f"Received invalid filter {order_by}")
            return queryset

        if order_by[0] == "-":
            order_by = order_by[1:]
            queryset = queryset.order_by(F(order_by).desc(nulls_last=True))
        else:
            queryset = queryset.order_by(F(order_by).asc(nulls_last=True))
        return queryset


class PublisherList(FilterableBaseListView):
    model = Publisher


class DeveloperList(FilterableBaseListView):
    model = Developer


class GenreList(FilterableBaseListView):
    model = Genre


class GameDetail(DetailView):
    model = Game


class GamePlayDetail(DetailView):
    template_name = "games/game_play_detail.html"
    model = Game


class GameSystemDetail(DetailView, MultipleObjectMixin):
    model = GameSystem
    paginate_by = 20

    def get_context_data(self, **kwargs):
        object_list = Game.objects.filter(game_system=self.get_object())
        context = super(GameSystemDetail, self).get_context_data(
            object_list=object_list, **kwargs
        )
        return context


class GenreDetail(DetailView, MultipleObjectMixin):
    model = Genre
    paginate_by = 20

    def get_context_data(self, **kwargs):
        object_list = Game.objects.filter(genre=self.get_object())
        context = super(GenreDetail, self).get_context_data(
            object_list=object_list, **kwargs
        )
        return context


class PublisherDetail(DetailView):
    model = Publisher
    paginate_by = 20

    def get_context_data(self, **kwargs):
        object_list = Game.objects.filter(publisher=self.get_object())
        context = super(PublisherDetail, self).get_context_data(
            object_list=object_list, **kwargs
        )
        return context


class DeveloperDetail(DetailView):
    model = Developer
    paginate_by = 20

    def get_context_data(self, **kwargs):
        object_list = Game.objects.filter(developer=self.get_object())
        context = super(DeveloperDetail, self).get_context_data(
            object_list=object_list, **kwargs
        )
        return context
