# Path: src/ctf_gameserver/web/registration/models.py
# class Team(models.Model):
#     """
#     Database representation of a team participating in the competition.
#     This enhances the user model, where the team name, password, formal email address etc. are stored. It is
#     particularly attuned to django.contrib.auth.models.User, but should work with other user models as well.
#     """
# 
#     user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key=True, on_delete=models.CASCADE)
# 
#     net_number = models.PositiveSmallIntegerField(null=True, unique=True)
#     informal_email = models.EmailField(_('Informal email address'))
#     image = ThumbnailImageField(upload_to=_gen_image_name, blank=True)
#     affiliation = models.CharField(max_length=100, blank=True)
#     country = models.CharField(max_length=100)
#     # NOP teams don't get included in the scoring
#     nop_team = models.BooleanField(default=False, db_index=True)
# 
#     class ActiveObjectsManager(models.Manager):
#         def get_queryset(self):
#             return super().get_queryset().filter(user__is_active=True)
# 
#     class ActiveNotNopObjectsManager(ActiveObjectsManager):
#         def get_queryset(self):
#             return super().get_queryset().filter(nop_team=False)
# 
#     # The first Manager in a class is used as default
#     objects = models.Manager()
#     # QuerySet that only returns Teams whose associated user object is not marked as inactive
#     active_objects = ActiveObjectsManager()
#     # QuerySet that only returns active Teams that are not marked as NOP team
#     active_not_nop_objects = ActiveNotNopObjectsManager()
# 
#     def __str__(self):
#         # pylint: disable=no-member
#         return self.user.username
# 
# Path: src/ctf_gameserver/web/registration/fields.py
# class ClearableThumbnailImageInput(ClearableFileInput):
#     """
#     Custom variant of the ClearableFileInput widget for rendering a ThumbnailImageField. It will display the
#     thumbnail image instead of the image's filename.
#     """
# 
#     def get_template_substitution_values(self, value):
#         return {
#             'initial': format_html('<img class="clearable-input-image" src="{}" alt="{}" />',
#                                    value.get_thumbnail_url(), str(value)),
#             'initial_url': conditional_escape(value.url),
#         }
# 
# Path: src/ctf_gameserver/web/registration/util.py
# class EmailConfirmationTokenGenerator(PasswordResetTokenGenerator):
#     def _make_hash_value(self, user, timestamp):
# def get_country_names():


from django import forms
from django.core.mail import send_mail
from django.template import loader
from django.conf import settings
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.models import User
from django.contrib.sites.shortcuts import get_current_site
from .models import Team
from .fields import ClearableThumbnailImageInput
from .util import email_token_generator, get_country_names
import ctf_gameserver.web.scoring.models as scoring_models

    def send_confirmation_mail(self, request):
        """
        Sends an email containing the address confirmation link to the user associated with this form. As it
        requires a User instance, it should only be called after the object has initially been saved.

        Args:
            request: The HttpRequest from which this function is being called
        """
        competition_name = scoring_models.GameControl.get_instance().competition_name

        context = {
            'competition_name': competition_name,
            'protocol': 'https' if request.is_secure() else 'http',
            'domain': get_current_site(request),
            'user': self.instance.pk,
            'token': email_token_generator.make_token(self.instance)
        }
        message = loader.render_to_string('confirmation_mail.txt', context)

        send_mail(competition_name+' email confirmation', message, settings.DEFAULT_FROM_EMAIL,
                  [self.instance.email])


class TeamForm(forms.ModelForm):
    """
    The portion of the registration form which ends up in the 'Team' model. Designed to be used in
    conjunction with UserForm.
    """


# Path: src/ctf_gameserver/web/registration/models.py
# class Team(models.Model):
#     """
#     Database representation of a team participating in the competition.
#     This enhances the user model, where the team name, password, formal email address etc. are stored. It is
#     particularly attuned to django.contrib.auth.models.User, but should work with other user models as well.
#     """
# 
#     user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key=True, on_delete=models.CASCADE)
# 
#     net_number = models.PositiveSmallIntegerField(null=True, unique=True)
#     informal_email = models.EmailField(_('Informal email address'))
#     image = ThumbnailImageField(upload_to=_gen_image_name, blank=True)
#     affiliation = models.CharField(max_length=100, blank=True)
#     country = models.CharField(max_length=100)
#     # NOP teams don't get included in the scoring
#     nop_team = models.BooleanField(default=False, db_index=True)
# 
#     class ActiveObjectsManager(models.Manager):
#         def get_queryset(self):
#             return super().get_queryset().filter(user__is_active=True)
# 
#     class ActiveNotNopObjectsManager(ActiveObjectsManager):
#         def get_queryset(self):
#             return super().get_queryset().filter(nop_team=False)
# 
#     # The first Manager in a class is used as default
#     objects = models.Manager()
#     # QuerySet that only returns Teams whose associated user object is not marked as inactive
#     active_objects = ActiveObjectsManager()
#     # QuerySet that only returns active Teams that are not marked as NOP team
#     active_not_nop_objects = ActiveNotNopObjectsManager()
# 
#     def __str__(self):
#         # pylint: disable=no-member
#         return self.user.username
# 
# Path: src/ctf_gameserver/web/registration/fields.py
# class ClearableThumbnailImageInput(ClearableFileInput):
#     """
#     Custom variant of the ClearableFileInput widget for rendering a ThumbnailImageField. It will display the
#     thumbnail image instead of the image's filename.
#     """
# 
#     def get_template_substitution_values(self, value):
#         return {
#             'initial': format_html('<img class="clearable-input-image" src="{}" alt="{}" />',
#                                    value.get_thumbnail_url(), str(value)),
#             'initial_url': conditional_escape(value.url),
#         }
# 
# Path: src/ctf_gameserver/web/registration/util.py
# class EmailConfirmationTokenGenerator(PasswordResetTokenGenerator):
#     def _make_hash_value(self, user, timestamp):
# def get_country_names():


# Path: src/ctf_gameserver/web/registration/forms.py
from django import forms
from django.core.mail import send_mail
from django.template import loader
from django.conf import settings
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.models import User
from django.contrib.sites.shortcuts import get_current_site
from .models import Team
from .fields import ClearableThumbnailImageInput
from .util import email_token_generator, get_country_names
import ctf_gameserver.web.scoring.models as scoring_models


    def send_confirmation_mail(self, request):
        """
        Sends an email containing the address confirmation link to the user associated with this form. As it
        requires a User instance, it should only be called after the object has initially been saved.

        Args:
            request: The HttpRequest from which this function is being called
        """
        competition_name = scoring_models.GameControl.get_instance().competition_name

        context = {
            'competition_name': competition_name,
            'protocol': 'https' if request.is_secure() else 'http',
            'domain': get_current_site(request),
            'user': self.instance.pk,
            'token': email_token_generator.make_token(self.instance)
        }
        message = loader.render_to_string('confirmation_mail.txt', context)

        send_mail(competition_name+' email confirmation', message, settings.DEFAULT_FROM_EMAIL,
                  [self.instance.email])


class TeamForm(forms.ModelForm):
    """
    The portion of the registration form which ends up in the 'Team' model. Designed to be used in
    conjunction with UserForm.
    """


    country = forms.ChoiceField(choices=[(name, name) for name in get_country_names()])