from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from django.shortcuts import get_object_or_404
from django.db.models import Q

from ..models import Game
from .mixins import CompetitionViewMixin, RequireRunningMixin


class GameView(CompetitionViewMixin, RequireRunningMixin):
    def parse_data(self, games):
        fields = set()
        for game in games:
            try:
                fields.add(*game.data['display'].keys())
            except (KeyError, TypeError, AttributeError):
                pass
        return fields


class GameListView(GameView, ListView):
    paginate_by = 25
    context_object_name = 'games'
    template_name = 'competition/game/game_list.html'

    def get_queryset(self):
        self.team = get_object_or_404(self.request.user.team_set,
                                      competition=self.get_competition())
        q = Game.objects.prefetch_related('team1', 'team2', 'competition')
        q = q.filter(Q(team1=self.team)|Q(team2=self.team))
        return q.order_by('start_time')

    def get_context_data(self, **kwargs):
        context = super(GameListView, self).get_context_data(**kwargs)
        context['data_fields'] = self.parse_data(context['page_obj'])
        context['team'] = self.team
        return context


class GameDetailView(GameView, DetailView):
    template_name = 'competition/game/game_detail.html'

    def get_queryset(self):
        self.team = get_object_or_404(self.request.user.team_set,
                                      competition=self.get_competition())
        return Game.objects.filter(Q(team1=self.team)|Q(team2=self.team))

    def get_context_data(self, **kwargs):
        context = super(GameDetailView, self).get_context_data(**kwargs)
        context['data_fields'] = self.parse_data([self.object])
        context['team'] = self.team
        return context

@@ -168,16 +168,48 @@
 import Q
+%0Afrom django.http import Http404
 %0A%0Afrom .
@@ -351,16 +351,279 @@
 Mixin):%0A
+%0A    def get_team(self):%0A        if self.request.user.is_anonymous():%0A            raise Http404(%22Anonymous user cannot view games%22)%0A        return get_object_or_404(self.request.user.team_set,%0A                                 competition=self.get_competition())%0A%0A
     def 
@@ -1076,126 +1076,22 @@
 m = 
-get_object_or_404(self.request.user.team_set,%0A                                      competition=self.get_competition()
+self.get_team(
 )%0A  
@@ -1661,126 +1661,22 @@
 m = 
-get_object_or_404(self.request.user.team_set,%0A                                      competition=self.get_competition()
+self.get_team(
 )%0A  

Check for AnonymousUser when getting games