# Path: foosball/games/stats.py
# def update_player_stats(instance):
# def stats_red_or_blue(params):
# def stats_players(params):
# 
# Path: foosball/games/forms.py
# class GameForm(SuperForm):
#     game = ModelFormField(GameModelForm)
#     team1 = ModelFormField(TeamModelForm)
#     team2 = ModelFormField(TeamModelForm)
# 
#     def is_valid(self):
#         return super().is_valid() & clean_team_forms(self.forms['team1'], self.forms['team2'])
# 
# Path: foosball/games/stats.py
# def update_player_stats(instance):
#     """
#     Update player win and played counts for players of a Team.
# 
#     :param instance: Team that will be used to update players.
#     :type instance: Team
#     """
#     for user in instance.players.all():
#         totals = {1: 0, 2: 0}
#         wins = {1: 0, 2: 0}
#         teams = Team.objects.filter(players__id=user.id).prefetch_related("players")
#         for team in teams:
#             player_count = len(team.players.all())
#             totals[player_count] += 1
#             if team.score == 10:
#                 wins[player_count] += 1
#         player, _created = Player.objects.get_or_create(user=user)
#         player.singles_wins = wins[1]
#         player.doubles_wins = wins[2]
#         player.singles_played = totals[1]
#         player.doubles_played = totals[2]
#         if totals[1]:
#             player.singles_win_percentage = round((wins[1]/totals[1])*100, 2)
#         else:
#             player.singles_win_percentage = 0
#         if totals[2]:
#             player.doubles_win_percentage = round((wins[2] / totals[2])*100, 2)
#         else:
#             player.doubles_win_percentage = 0
#         player.total_played = totals[1] + totals[2]
#         player.save()
# 
# Path: foosball/games/models.py
# class Game(TimeStampedModel):
#     created_by = models.ForeignKey(
#         User, related_name="games_created", editable=False, null=True, verbose_name=_("created by")
#     )
#     modified_by = models.ForeignKey(
#         User, related_name="games_modified", editable=False, null=True, verbose_name=_("modified by")
#     )
# 
#     played_at = models.DateTimeField(
#         default=timezone.now,
#         verbose_name=_("played at"),
#         help_text=_("Time when the game was played")
#     )
# 
#     table = models.ForeignKey(Table, blank=True, null=True, related_name="games", verbose_name=_("table"))
# 
#     class Meta:
#         ordering = ['-played_at']
# 
#     def __str__(self):
#         return " - ".join(map(str, self.teams.all()))
# 
# class Team(models.Model):
#     UNKNOWN = 0
#     RED = 1
#     BLUE = 2
#     SIDE_CHOICES = (
#         (UNKNOWN, _("Unknown")),
#         (RED, _("Red")),
#         (BLUE, _("Blue")),
#     )
#     side = models.IntegerField(db_index=True, choices=SIDE_CHOICES, default=UNKNOWN, verbose_name=_("side"))
# 
#     game = models.ForeignKey(Game, related_name="teams", on_delete=models.CASCADE)
#     score = models.PositiveSmallIntegerField(
#         verbose_name=_("score"),
#         help_text=_("Team's score in the game"),
#         validators=[MaxValueValidator(limit_value=10)]
#     )
#     players = models.ManyToManyField(User)
# 
#     def __str__(self):
#         return "%s (%s)" % (
#             self.score,
#             ", ".join(map(str, self.players.all()))
#         )


import inspect
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.urlresolvers import reverse_lazy
from django.db import transaction
from django.http.response import HttpResponseBadRequest, JsonResponse
from django.shortcuts import redirect
from django.views.generic import ListView, DetailView, FormView, View
from foosball.games import stats
from foosball.games.forms import GameForm
from foosball.games.stats import update_player_stats
from .models import Game, Team




class GameListView(LoginRequiredMixin, ListView):
    model = Game
    paginate_by = 10
    template_name = "games/game_list.jinja"


class GameDetailView(LoginRequiredMixin, DetailView):
    model = Game
    template_name = "games/game_detail.jinja"


class GameCreateView(LoginRequiredMixin, FormView):
    template_name = "games/game_new.jinja"
    form_class = GameForm
    success_url = reverse_lazy("games:index")

    @transaction.atomic
    def form_valid(self, form):
        game = form.forms['game'].save(commit=False)
        game.created_by = game.modified_by = self.request.user
        game.save()

        self._save_team_score(game, Team.RED, form.forms['team1'])

# Path: foosball/games/stats.py
# def update_player_stats(instance):
# def stats_red_or_blue(params):
# def stats_players(params):
# 
# Path: foosball/games/forms.py
# class GameForm(SuperForm):
#     game = ModelFormField(GameModelForm)
#     team1 = ModelFormField(TeamModelForm)
#     team2 = ModelFormField(TeamModelForm)
# 
#     def is_valid(self):
#         return super().is_valid() & clean_team_forms(self.forms['team1'], self.forms['team2'])
# 
# Path: foosball/games/stats.py
# def update_player_stats(instance):
#     """
#     Update player win and played counts for players of a Team.
# 
#     :param instance: Team that will be used to update players.
#     :type instance: Team
#     """
#     for user in instance.players.all():
#         totals = {1: 0, 2: 0}
#         wins = {1: 0, 2: 0}
#         teams = Team.objects.filter(players__id=user.id).prefetch_related("players")
#         for team in teams:
#             player_count = len(team.players.all())
#             totals[player_count] += 1
#             if team.score == 10:
#                 wins[player_count] += 1
#         player, _created = Player.objects.get_or_create(user=user)
#         player.singles_wins = wins[1]
#         player.doubles_wins = wins[2]
#         player.singles_played = totals[1]
#         player.doubles_played = totals[2]
#         if totals[1]:
#             player.singles_win_percentage = round((wins[1]/totals[1])*100, 2)
#         else:
#             player.singles_win_percentage = 0
#         if totals[2]:
#             player.doubles_win_percentage = round((wins[2] / totals[2])*100, 2)
#         else:
#             player.doubles_win_percentage = 0
#         player.total_played = totals[1] + totals[2]
#         player.save()
# 
# Path: foosball/games/models.py
# class Game(TimeStampedModel):
#     created_by = models.ForeignKey(
#         User, related_name="games_created", editable=False, null=True, verbose_name=_("created by")
#     )
#     modified_by = models.ForeignKey(
#         User, related_name="games_modified", editable=False, null=True, verbose_name=_("modified by")
#     )
# 
#     played_at = models.DateTimeField(
#         default=timezone.now,
#         verbose_name=_("played at"),
#         help_text=_("Time when the game was played")
#     )
# 
#     table = models.ForeignKey(Table, blank=True, null=True, related_name="games", verbose_name=_("table"))
# 
#     class Meta:
#         ordering = ['-played_at']
# 
#     def __str__(self):
#         return " - ".join(map(str, self.teams.all()))
# 
# class Team(models.Model):
#     UNKNOWN = 0
#     RED = 1
#     BLUE = 2
#     SIDE_CHOICES = (
#         (UNKNOWN, _("Unknown")),
#         (RED, _("Red")),
#         (BLUE, _("Blue")),
#     )
#     side = models.IntegerField(db_index=True, choices=SIDE_CHOICES, default=UNKNOWN, verbose_name=_("side"))
# 
#     game = models.ForeignKey(Game, related_name="teams", on_delete=models.CASCADE)
#     score = models.PositiveSmallIntegerField(
#         verbose_name=_("score"),
#         help_text=_("Team's score in the game"),
#         validators=[MaxValueValidator(limit_value=10)]
#     )
#     players = models.ManyToManyField(User)
# 
#     def __str__(self):
#         return "%s (%s)" % (
#             self.score,
#             ", ".join(map(str, self.players.all()))
#         )


# Path: foosball/games/views.py
import inspect
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.urlresolvers import reverse_lazy
from django.db import transaction
from django.http.response import HttpResponseBadRequest, JsonResponse
from django.shortcuts import redirect
from django.views.generic import ListView, DetailView, FormView, View
from foosball.games import stats
from foosball.games.forms import GameForm
from foosball.games.stats import update_player_stats
from .models import Game, Team





class GameListView(LoginRequiredMixin, ListView):
    model = Game
    paginate_by = 10
    template_name = "games/game_list.jinja"


class GameDetailView(LoginRequiredMixin, DetailView):
    model = Game
    template_name = "games/game_detail.jinja"


class GameCreateView(LoginRequiredMixin, FormView):
    template_name = "games/game_new.jinja"
    form_class = GameForm
    success_url = reverse_lazy("games:index")

    @transaction.atomic
    def form_valid(self, form):
        game = form.forms['game'].save(commit=False)
        game.created_by = game.modified_by = self.request.user
        game.save()

        self._save_team_score(game, Team.RED, form.forms['team1'])

        self._save_team_score(game, Team.BLUE, form.forms['team2'])