# Path: challenges/models.py
# class Challenge(models.Model):
#     objects = ChallengeQuerySet.as_manager()
# 
#     name = models.CharField(max_length=256)
#     category = models.ForeignKey('challenges.Category', related_name='challenges', on_delete=models.CASCADE)
#     description = models.TextField()
#     key = models.CharField(max_length=256)
#     points = models.IntegerField()
#     difficulty = models.CharField(max_length=1, choices=(
#         ('E', 'Easy'),
#         ('M', 'Medium'),
#         ('H', 'Hard')
#     ))
# 
#     solved_by = models.ManyToManyField(RelatedUserModel,
#                                        related_name='solved_challenges',
#                                        through='challenges.ChallengeSolved')
# 
#     failed_by = models.ManyToManyField(RelatedUserModel,
#                                        related_name='_all_failed_challenges',
#                                        through='challenges.ChallengeFail')
# 
#     @property
#     def newest_solved(self):
#         return self.challengesolved_set.order_by('-datetime')
# 
#     def __str__(self):
#         return self.name
# 
# class Category(models.Model):
#     name = models.CharField(max_length=256, unique=True)
#     description = models.TextField()
# 
#     class Meta:
#         verbose_name_plural = "categories"
# 
#     def __str__(self):
#         return self.name
# 
# class ChallengeSolved(models.Model):
#     user = models.ForeignKey(RelatedUserModel, on_delete=models.CASCADE)
#     challenge = models.ForeignKey('challenges.Challenge', on_delete=models.CASCADE)
#     datetime = models.DateTimeField(auto_now_add=True)
# 
#     def __str__(self):
#         return 'Challenge: {}, User: {}'.format(self.challenge.name, self.user)
# 
# class ChallengeFail(models.Model):
#     user = models.ForeignKey(RelatedUserModel, on_delete=models.CASCADE)
#     challenge = models.ForeignKey('challenges.Challenge', on_delete=models.CASCADE)
#     datetime = models.DateTimeField(auto_now_add=True)
# 
#     def __str__(self):
#         return 'Challenge: {}, User: {}'.format(self.challenge.name, self.user)
# 
# Path: challenges/serializers.py
# class ChallengeSolvedSerializer(serializers.ModelSerializer):
#     key = serializers.CharField()
# 
#     class Meta:
#         model = ChallengeSolved
#         fields = ('challenge', 'key')
# 
# Path: accounts/models.py
# class Team(models.Model, StatsFromChallengesMixin):
#     objects = TeamQuerySet.as_manager()
# 
#     name = models.CharField(max_length=256, unique=True)
#     users = models.ManyToManyField(User, through='accounts.userprofile')
#     created_at = models.DateTimeField(auto_now_add=True, editable=False)
#     created_by = models.ForeignKey(User, related_name='created_team', on_delete=models.CASCADE)
# 
#     @property
#     def num_users(self):
#         return self.users.count()
# 
#     @property
#     def challengesolved_set(self):
#         from challenges.models import ChallengeSolved
#         return ChallengeSolved.objects.filter(user__team=self)
# 
#     @property
#     def solved_challenges(self):
#         from challenges.models import Challenge
#         return Challenge.objects.filter(solved_by__team=self).distinct()
# 
#     @property
#     def failed_challenges(self):
#         from challenges.models import Challenge
#         return Challenge.objects\
#             .filter(failed_by__team=self)\
#             .distinct()\
#             .exclude(pk__in=self.solved_challenges.all())
# 
#     def __str__(self):
#         return self.name
# 
# class UserProfile(models.Model, StatsFromChallengesMixin):
#     objects = UserProfileQuerySet.as_manager()
# 
#     team = models.ForeignKey('accounts.Team', null=True, blank=True, on_delete=models.CASCADE)
#     user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE)
#     created_at = models.DateTimeField(auto_now_add=True)
#     image = models.FileField(upload_to='accounts/', default='accounts/user.png')
#     job = models.CharField(max_length=255)
#     gender = models.CharField(max_length=1, choices=(('M', 'Male'), ('F','Female')))
#     website = models.CharField(max_length=255, null=True, blank=True)
#     country = models.ForeignKey(Country, on_delete=models.CASCADE)
#     skills = models.TextField(null=True, blank=True)
# 
#     @property
#     def skill_list(self):
#         return self.skills.split(SKILLS_SEPARATOR) if self.skills else []
# 
#     def __str__(self):
#         return '{}, Team: {}'.format(self.user.username, self.team)
# 
#     @property
#     def failed_challenges(self):
#         return self._all_failed_challenges.exclude(pk__in=self.solved_challenges.all())
# 
# Path: SCTF/consumers.py
# def send_message(dict_message, group='all'):
#     Group(group).send({"text": json.dumps(dict_message)})


import json
from rest_framework.generics import get_object_or_404
from rest_framework.mixins import CreateModelMixin
from rest_framework.response import Response
from rest_framework.status import HTTP_417_EXPECTATION_FAILED, HTTP_412_PRECONDITION_FAILED
from rest_framework.viewsets import GenericViewSet
from challenges.models import Challenge, Category, ChallengeSolved, ChallengeFail
from challenges.serializers import ChallengeSolvedSerializer
from django.shortcuts import render
from accounts.models import Team, UserProfile
from SCTF.consumers import send_message






def challenges_categories(request):
    categories = Category.objects.all()
    
    user = request.user
    team = user.profile.team
    categories_num_done_user = [
        c.challenges.filter(solved_by=user.profile).distinct().count()
        for c in categories
    ]
    categories_num_done_team = [
        c.challenges.filter(solved_by__team=team).distinct().count()
        for c in categories
    ]


# Path: challenges/models.py
# class Challenge(models.Model):
#     objects = ChallengeQuerySet.as_manager()
# 
#     name = models.CharField(max_length=256)
#     category = models.ForeignKey('challenges.Category', related_name='challenges', on_delete=models.CASCADE)
#     description = models.TextField()
#     key = models.CharField(max_length=256)
#     points = models.IntegerField()
#     difficulty = models.CharField(max_length=1, choices=(
#         ('E', 'Easy'),
#         ('M', 'Medium'),
#         ('H', 'Hard')
#     ))
# 
#     solved_by = models.ManyToManyField(RelatedUserModel,
#                                        related_name='solved_challenges',
#                                        through='challenges.ChallengeSolved')
# 
#     failed_by = models.ManyToManyField(RelatedUserModel,
#                                        related_name='_all_failed_challenges',
#                                        through='challenges.ChallengeFail')
# 
#     @property
#     def newest_solved(self):
#         return self.challengesolved_set.order_by('-datetime')
# 
#     def __str__(self):
#         return self.name
# 
# class Category(models.Model):
#     name = models.CharField(max_length=256, unique=True)
#     description = models.TextField()
# 
#     class Meta:
#         verbose_name_plural = "categories"
# 
#     def __str__(self):
#         return self.name
# 
# class ChallengeSolved(models.Model):
#     user = models.ForeignKey(RelatedUserModel, on_delete=models.CASCADE)
#     challenge = models.ForeignKey('challenges.Challenge', on_delete=models.CASCADE)
#     datetime = models.DateTimeField(auto_now_add=True)
# 
#     def __str__(self):
#         return 'Challenge: {}, User: {}'.format(self.challenge.name, self.user)
# 
# class ChallengeFail(models.Model):
#     user = models.ForeignKey(RelatedUserModel, on_delete=models.CASCADE)
#     challenge = models.ForeignKey('challenges.Challenge', on_delete=models.CASCADE)
#     datetime = models.DateTimeField(auto_now_add=True)
# 
#     def __str__(self):
#         return 'Challenge: {}, User: {}'.format(self.challenge.name, self.user)
# 
# Path: challenges/serializers.py
# class ChallengeSolvedSerializer(serializers.ModelSerializer):
#     key = serializers.CharField()
# 
#     class Meta:
#         model = ChallengeSolved
#         fields = ('challenge', 'key')
# 
# Path: accounts/models.py
# class Team(models.Model, StatsFromChallengesMixin):
#     objects = TeamQuerySet.as_manager()
# 
#     name = models.CharField(max_length=256, unique=True)
#     users = models.ManyToManyField(User, through='accounts.userprofile')
#     created_at = models.DateTimeField(auto_now_add=True, editable=False)
#     created_by = models.ForeignKey(User, related_name='created_team', on_delete=models.CASCADE)
# 
#     @property
#     def num_users(self):
#         return self.users.count()
# 
#     @property
#     def challengesolved_set(self):
#         from challenges.models import ChallengeSolved
#         return ChallengeSolved.objects.filter(user__team=self)
# 
#     @property
#     def solved_challenges(self):
#         from challenges.models import Challenge
#         return Challenge.objects.filter(solved_by__team=self).distinct()
# 
#     @property
#     def failed_challenges(self):
#         from challenges.models import Challenge
#         return Challenge.objects\
#             .filter(failed_by__team=self)\
#             .distinct()\
#             .exclude(pk__in=self.solved_challenges.all())
# 
#     def __str__(self):
#         return self.name
# 
# class UserProfile(models.Model, StatsFromChallengesMixin):
#     objects = UserProfileQuerySet.as_manager()
# 
#     team = models.ForeignKey('accounts.Team', null=True, blank=True, on_delete=models.CASCADE)
#     user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE)
#     created_at = models.DateTimeField(auto_now_add=True)
#     image = models.FileField(upload_to='accounts/', default='accounts/user.png')
#     job = models.CharField(max_length=255)
#     gender = models.CharField(max_length=1, choices=(('M', 'Male'), ('F','Female')))
#     website = models.CharField(max_length=255, null=True, blank=True)
#     country = models.ForeignKey(Country, on_delete=models.CASCADE)
#     skills = models.TextField(null=True, blank=True)
# 
#     @property
#     def skill_list(self):
#         return self.skills.split(SKILLS_SEPARATOR) if self.skills else []
# 
#     def __str__(self):
#         return '{}, Team: {}'.format(self.user.username, self.team)
# 
#     @property
#     def failed_challenges(self):
#         return self._all_failed_challenges.exclude(pk__in=self.solved_challenges.all())
# 
# Path: SCTF/consumers.py
# def send_message(dict_message, group='all'):
#     Group(group).send({"text": json.dumps(dict_message)})


# Path: challenges/views.py
import json
from rest_framework.generics import get_object_or_404
from rest_framework.mixins import CreateModelMixin
from rest_framework.response import Response
from rest_framework.status import HTTP_417_EXPECTATION_FAILED, HTTP_412_PRECONDITION_FAILED
from rest_framework.viewsets import GenericViewSet
from challenges.models import Challenge, Category, ChallengeSolved, ChallengeFail
from challenges.serializers import ChallengeSolvedSerializer
from django.shortcuts import render
from accounts.models import Team, UserProfile
from SCTF.consumers import send_message







def challenges_categories(request):
    categories = Category.objects.all()
    
    user = request.user
    team = user.profile.team
    categories_num_done_user = [
        c.challenges.filter(solved_by=user.profile).distinct().count()
        for c in categories
    ]
    categories_num_done_team = [
        c.challenges.filter(solved_by__team=team).distinct().count()
        for c in categories
    ]


    last_team_solutions = ChallengeSolved.objects\