from rest_framework import serializers
from tournaments.models.court import Court
from tournaments.models import Club, LiveMatch, TeamScore, Tournament, CustomUser, Event, Round, GroupStage, Match, TeamRegistration, PlayerRegistration, Purchase, FailedApiCall, DateInterval, Log, DeviceToken
from django.contrib.auth import password_validation
from django.utils.translation import gettext_lazy as _
# email
from django.template.loader import render_to_string
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from django.utils.encoding import force_bytes
from django.core.mail import EmailMessage
from django.contrib.sites.shortcuts import get_current_site

from api.tokens import account_activation_token

class UserSerializer(serializers.ModelSerializer):

    password = serializers.CharField(write_only=True)

    def create(self, validated_data):

        # print(validated_data)
        umpire_code = None
        if 'umpire_code' in validated_data:
            umpire_code = validated_data['umpire_code']
        phone = None
        if 'phone' in validated_data:
            phone = validated_data['phone']
        licence_id = None
        if 'licence_id' in validated_data:
            licence_id = validated_data['licence_id']
        country = None
        if 'country' in validated_data:
            country = validated_data['country']

        user = CustomUser.objects.create_user(
            username=validated_data['username'],
            email=validated_data['email'],
            password=validated_data['password'],
            first_name=validated_data['first_name'],
            last_name=validated_data['last_name'],
            is_active=False,
            umpire_code=umpire_code,
            phone=phone,
            licence_id=licence_id,
            country=country,
            summons_message_body=validated_data.get('summons_message_body'),
            summons_message_signature=validated_data.get('summons_message_signature'),
            summons_available_payment_methods=validated_data.get('summons_available_payment_methods'),
            summons_display_format=validated_data.get('summons_display_format'),
            summons_display_entry_fee=validated_data.get('summons_display_entry_fee'),
            summons_use_full_custom_message=validated_data.get('summons_use_full_custom_message'),
            match_formats_default_duration=validated_data.get('match_formats_default_duration'),
            bracket_match_format_preference=validated_data.get('bracket_match_format_preference'),
            group_stage_match_format_preference=validated_data.get('group_stage_match_format_preference'),
            loser_bracket_match_format_preference=validated_data.get('loser_bracket_match_format_preference'),
        )

        self.send_email(self.context['request'], user)
        # RegistrationProfile.objects.filter(user=user).send_activation_email()

        return user

    def send_email(self, request, user):

        current_site = get_current_site(request)
        mail_subject = 'Activez votre compte Padel Club !'
        message = render_to_string('tournaments/acc_active_email.html', {
            'user': user,
            'domain': current_site.domain,
            'uid': urlsafe_base64_encode(force_bytes(user.pk)),
            'token': account_activation_token.make_token(user),
        })
        email = EmailMessage(mail_subject, message, to=[user.email])
        email.send()

    class Meta:
        club_id = serializers.PrimaryKeyRelatedField(queryset=Club.objects.all())
        model = CustomUser
        fields = '__all__' # ['id', 'username', 'password', 'umpire_code', 'clubs', 'phone', 'first_name', 'last_name', 'licence_id']

class UserUpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = CustomUser
        fields = CustomUser.fields_for_update()

class ClubSerializer(serializers.ModelSerializer):
    class Meta:
        model = Club
        fields = '__all__' # ['id', 'name', 'acronym', 'phone', 'code', 'federal_club_data', 'address', 'city', 'zip_code', 'latitude', 'longitude']

class TournamentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Tournament
        fields = '__all__'
          # ['id', 'name', 'event', 'creator_id', 'start_date', 'end_date', 'creation_date',
          #   'is_private', 'format', 'group_stage_format', 'round_format', 'loser_round_format', 'bracket_sort_mode',
          #   'group_stage_count', 'rank_source_date', 'day_duration', 'team_count', 'team_sorting',
          #   'federal_category', 'federal_level_category', 'federal_age_category', 'group_stage_court_count',
          #   'seed_count', 'closed_registration_date', 'group_stage_additional_qualified', 'court_count', 'prioritize_club_members',
          #   'qualified_per_group_stage', 'teams_per_group_stage']

class EventSerializer(serializers.ModelSerializer):
    class Meta:
        #club_id = serializers.PrimaryKeyRelatedField(queryset=Club.objects.all())
        model = Event
        fields = '__all__'
        # ['id', 'club_id', 'date', 'name', 'federal_tournament_data', 'court_count', 'tenup_id',
            # 'group_stage_format', 'round_format', 'loser_round_format']

class RoundSerializer(serializers.ModelSerializer):
    class Meta:
        # tournament_id = serializers.PrimaryKeyRelatedField(queryset=Tournament.objects.all())
        # loser_id = serializers.PrimaryKeyRelatedField(queryset=Round.objects.all())
        model = Round
        fields = '__all__' #['id', 'index', 'tournament_id', 'loser', 'format']

class GroupStageSerializer(serializers.ModelSerializer):
    class Meta:
        model = GroupStage
        fields = '__all__' # ['id', 'index', 'tournament_id', 'format']

class MatchSerializer(serializers.ModelSerializer):
    class Meta:
        # round_id = serializers.PrimaryKeyRelatedField(queryset=Round.objects.all())
        # group_stage_id = serializers.PrimaryKeyRelatedField(queryset=GroupStage.objects.all())
        model = Match
        fields = '__all__'
        # ['id', 'round_id', 'group_stage_id', 'index', 'format', 'court', 'start_date', 'end_date',
        #     'serving_team_id', 'winning_team_id', 'losing_team_id']

class TeamScoreSerializer(serializers.ModelSerializer):
    class Meta:
        # match_id = serializers.PrimaryKeyRelatedField(queryset=Match.objects.all())
        # player_registrations_ids = serializers.Man
        model = TeamScore
        fields = '__all__' # ['id', 'match_id', 'score', 'walk_out', 'lucky_loser', 'player_registrations']

class TeamRegistrationSerializer(serializers.ModelSerializer):
    class Meta:
        # match_id = serializers.PrimaryKeyRelatedField(queryset=Match.objects.all())
        # group_stage_id = serializers.PrimaryKeyRelatedField(queryset=GroupStage.objects.all())
        model = TeamRegistration
        fields = '__all__'
        # ['id', 'group_stage_id', 'registration_date', 'call_date', 'bracket_position',
        #     'group_stage_position', 'logo']

class PlayerRegistrationSerializer(serializers.ModelSerializer):
    class Meta:
        # team_registration_id = serializers.PrimaryKeyRelatedField(queryset=TeamRegistration.objects.all())
        # team_state_id = serializers.PrimaryKeyRelatedField(queryset=TeamState.objects.all())
        model = PlayerRegistration
        fields = '__all__'
        # ['id', 'team_registration_id', 'first_name', 'last_name', 'licence_id', 'rank', 'has_paid']

class PurchaseSerializer(serializers.ModelSerializer):
    class Meta:
        model = Purchase
        fields = '__all__'

class ChangePasswordSerializer(serializers.Serializer):
    old_password = serializers.CharField(max_length=128, write_only=True, required=True)
    new_password1 = serializers.CharField(max_length=128, write_only=True, required=True)
    new_password2 = serializers.CharField(max_length=128, write_only=True, required=True)

    def validate_old_password(self, value):
        user = self.context['request'].user
        if not user.check_password(value):
            raise serializers.ValidationError(
                _('Your old password was entered incorrectly. Please enter it again.')
            )
        return value

    def validate(self, data):
        if data['new_password1'] != data['new_password2']:
            raise serializers.ValidationError({'new_password2': _("The two password fields didn't match.")})
        password_validation.validate_password(data['new_password1'], self.context['request'].user)
        return data

    def save(self, **kwargs):
        password = self.validated_data['new_password1']
        user = self.context['request'].user
        user.set_password(password)
        user.save()
        return user

class LiveMatchSerializer(serializers.ModelSerializer):
    class Meta:
        model = LiveMatch
        fields = '__all__' # ['title', 'date'] # Serialize all fields of the model

class CourtSerializer(serializers.ModelSerializer):
    class Meta:
        model = Court
        fields = '__all__'

class DateIntervalSerializer(serializers.ModelSerializer):
    class Meta:
        model = DateInterval
        fields = '__all__'

class FailedApiCallSerializer(serializers.ModelSerializer):
    class Meta:
        model = FailedApiCall
        fields = '__all__'

class LogSerializer(serializers.ModelSerializer):
    class Meta:
        model = Log
        fields = '__all__'

class DeviceTokenSerializer(serializers.ModelSerializer):
    class Meta:
        model = DeviceToken
        fields = '__all__'
        read_only_fields = ['user']
