# Path: ladder/models.py
# class Result(models.Model):
#     ladder = models.ForeignKey(Ladder, on_delete=models.CASCADE)
#     player = models.ForeignKey(Player,on_delete=models.CASCADE, related_name='result_player')
#     opponent = models.ForeignKey(Player, on_delete=models.CASCADE, related_name='result_opponent')
#     result = models.IntegerField()
#     date_added = models.DateField('Date added')
#     inaccurate_flag = models.BooleanField(default=None)
# 
#     def __str__(self):
#         return (self.player.first_name + ' ' + self.player.last_name) + ' vs ' + (
#             self.opponent.first_name + ' ' + self.opponent.last_name) + (' score: ' + str(self.result))
# 
# class Player(models.Model):
#     first_name = models.CharField(max_length=100)
#     last_name = models.CharField(max_length=100)
#     user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, blank=True)
# 
#     def __str__(self):
#         return self.full_name(authenticated=False)
# 
#     def full_name(self, authenticated = False):
#         string = self.first_name
#         if self.last_name:
#             last_names = self.last_name.split()
#             if not authenticated:
#                 last_names[-1] = last_names[-1][:1].capitalize() + '.'  # abbreviate last name
#             string += ' ' + ' '.join(last_names)
# 
#         return string
# 
#     def player_stats(self):
#         """
#         Calculates stats about the players historical performance.
#         """
#         played = self.result_player.count()
#         won = float(self.result_player.filter(result=9).count())
#         lost = played - won  # more efficient than doing a count on the object
# 
#         # safe division (not by 0)
#         if played != 0:
#             win_rate = won / float(played) * 100.00
#             # 2 points for winning, 1 for playing
#             additional_points = ((won * 2) + played) / played
#         else:
#             return {
#                 'played': "-",
#                 'win_rate': "- %",
#                 'average': "-"
#             }
# 
#         # work out the average with additional points
#         average = list(self.result_player.aggregate(Avg('result')).values())[0]
#         average_with_additional = average + additional_points
# 
#         leagues = self.league_set.filter(player=self)
# 
#         match_count = 0
#         for league in leagues:
#             # count other players in ladder minus the player to get games
#             match_count += league.ladder.league_set.count() - 1
# 
#         completion_rate = float(played) / float(match_count) * 100.00
# 
#         return {
#             'played': played,
#             'win_rate': "{0:.2f} %".format(win_rate),
#             'completion_rate': "{0:.2f} %".format(completion_rate),
#             'average': "{0:.2f}".format(average_with_additional)
#         }


from django import forms
from ladder.models import Result, Player


class AddResultForm(forms.ModelForm):
    result = forms.IntegerField(min_value=0, max_value=8, label='Losing Result')

    # filter the player fields by ladder on init
    def __init__(self, ladder, *args, **kwargs):
        super(AddResultForm, self).__init__(*args, **kwargs)  # populates the post

# Path: ladder/models.py
# class Result(models.Model):
#     ladder = models.ForeignKey(Ladder, on_delete=models.CASCADE)
#     player = models.ForeignKey(Player,on_delete=models.CASCADE, related_name='result_player')
#     opponent = models.ForeignKey(Player, on_delete=models.CASCADE, related_name='result_opponent')
#     result = models.IntegerField()
#     date_added = models.DateField('Date added')
#     inaccurate_flag = models.BooleanField(default=None)
# 
#     def __str__(self):
#         return (self.player.first_name + ' ' + self.player.last_name) + ' vs ' + (
#             self.opponent.first_name + ' ' + self.opponent.last_name) + (' score: ' + str(self.result))
# 
# class Player(models.Model):
#     first_name = models.CharField(max_length=100)
#     last_name = models.CharField(max_length=100)
#     user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, blank=True)
# 
#     def __str__(self):
#         return self.full_name(authenticated=False)
# 
#     def full_name(self, authenticated = False):
#         string = self.first_name
#         if self.last_name:
#             last_names = self.last_name.split()
#             if not authenticated:
#                 last_names[-1] = last_names[-1][:1].capitalize() + '.'  # abbreviate last name
#             string += ' ' + ' '.join(last_names)
# 
#         return string
# 
#     def player_stats(self):
#         """
#         Calculates stats about the players historical performance.
#         """
#         played = self.result_player.count()
#         won = float(self.result_player.filter(result=9).count())
#         lost = played - won  # more efficient than doing a count on the object
# 
#         # safe division (not by 0)
#         if played != 0:
#             win_rate = won / float(played) * 100.00
#             # 2 points for winning, 1 for playing
#             additional_points = ((won * 2) + played) / played
#         else:
#             return {
#                 'played': "-",
#                 'win_rate': "- %",
#                 'average': "-"
#             }
# 
#         # work out the average with additional points
#         average = list(self.result_player.aggregate(Avg('result')).values())[0]
#         average_with_additional = average + additional_points
# 
#         leagues = self.league_set.filter(player=self)
# 
#         match_count = 0
#         for league in leagues:
#             # count other players in ladder minus the player to get games
#             match_count += league.ladder.league_set.count() - 1
# 
#         completion_rate = float(played) / float(match_count) * 100.00
# 
#         return {
#             'played': played,
#             'win_rate': "{0:.2f} %".format(win_rate),
#             'completion_rate': "{0:.2f} %".format(completion_rate),
#             'average': "{0:.2f}".format(average_with_additional)
#         }


# Path: ladder/forms.py
from django import forms
from ladder.models import Result, Player



class AddResultForm(forms.ModelForm):
    result = forms.IntegerField(min_value=0, max_value=8, label='Losing Result')

    # filter the player fields by ladder on init
    def __init__(self, ladder, *args, **kwargs):
        super(AddResultForm, self).__init__(*args, **kwargs)  # populates the post

        self.fields['opponent'].queryset = self.fields['player'].queryset = Player.objects.filter(league__ladder=ladder)