# Path: ladder/models.py
# 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.contrib.auth.models import User, Group
from ladder.models import Player
import uuid

group_object = Group.objects.get(name='player')

for player in players:
    first_name = player[0]
    last_name = player[1]
    email = player[2]

    if not email:
        print(first_name + " " + last_name + ": No Email")
        continue

    if User.objects.filter(username=email).exists():
        user_object = User.objects.get_by_natural_key(email)
    else:
        user_object = User(
            username=email,
            email=email,
            first_name=first_name,
            last_name=last_name,
            is_staff=False,
            is_superuser=False
        )
        user_object.set_password(uuid.uuid4().hex)
        user_object.save()

    user_object.groups.add(group_object)
    user_object.save()

    try:

# Path: ladder/models.py
# 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/management/shell/import_users.py
from django.contrib.auth.models import User, Group
from ladder.models import Player
import uuid


group_object = Group.objects.get(name='player')

for player in players:
    first_name = player[0]
    last_name = player[1]
    email = player[2]

    if not email:
        print(first_name + " " + last_name + ": No Email")
        continue

    if User.objects.filter(username=email).exists():
        user_object = User.objects.get_by_natural_key(email)
    else:
        user_object = User(
            username=email,
            email=email,
            first_name=first_name,
            last_name=last_name,
            is_staff=False,
            is_superuser=False
        )
        user_object.set_password(uuid.uuid4().hex)
        user_object.save()

    user_object.groups.add(group_object)
    user_object.save()

    try:

        player_object = Player.objects.get(first_name=first_name, last_name=last_name)