from .serializers import ClubSerializer, CourtSerializer, DateIntervalSerializer, TournamentSerializer, UserSerializer, ChangePasswordSerializer, EventSerializer, RoundSerializer, GroupStageSerializer, MatchSerializer, TeamScoreSerializer, TeamRegistrationSerializer, PlayerRegistrationSerializer, LiveMatchSerializer, PurchaseSerializer, UserUpdateSerializer, FailedApiCallSerializer, LogSerializer, DeviceTokenSerializer
from tournaments.models import Club, Tournament, CustomUser, Event, Round, GroupStage, Match, TeamScore, TeamRegistration, PlayerRegistration, Court, DateInterval, Purchase, FailedApiCall, Log, DeviceToken

from rest_framework import viewsets, permissions
from rest_framework.authtoken.models import Token
from rest_framework.response import Response
from rest_framework.decorators import api_view
from rest_framework import status
from rest_framework.generics import UpdateAPIView
from rest_framework.exceptions import MethodNotAllowed
from rest_framework.permissions import IsAuthenticated

from django.contrib.auth import authenticate
from rest_framework.views import APIView

from django.db.models import Q

from .permissions import IsClubOwner

class CustomAuthToken(APIView):
    permission_classes = []

    def post(self, request, *args, **kwargs):
        username = request.data.get('username')
        password = request.data.get('password')
        device_id = request.data.get('device_id')
        user = authenticate(username=username, password=password)

        if user is not None:

            if user.device_id is None or user.device_id == device_id or user.username == 'apple-test':
                user.device_id = device_id
                user.save()

                token, created = Token.objects.get_or_create(user=user)
                return Response({'token': token.key})
            else:
                return Response({'error': 'Vous ne pouvez pour l\'instant vous connecter sur plusieurs appareils en même temps. Veuillez vous déconnecter du précédent appareil. Autrement, veuillez contacter le support.'}, status=status.HTTP_403_FORBIDDEN)
        else:
            return Response({'error': 'L\'utilisateur et le mot de passe de correspondent pas'}, status=status.HTTP_401_UNAUTHORIZED)

class Logout(APIView):
    permission_classes = (IsAuthenticated,)

    def post(self, request, *args, **kwargs):
        request.user.auth_token.delete()

        device_id = request.data.get('device_id')
        if request.user.device_id == device_id:
            request.user.device_id = None
            request.user.save()

        return Response(status=status.HTTP_200_OK)

@api_view(['GET'])
def user_by_token(request):
    serializer = UserSerializer(request.user)
    return Response(serializer.data, status=status.HTTP_200_OK)

class UserViewSet(viewsets.ModelViewSet):
    queryset = CustomUser.objects.all()
    serializer_class = UserUpdateSerializer
    permission_classes = [] # Users are public whereas the other requests are only for logged users

    def get_serializer_class(self):
        # Use UserSerializer for other actions (e.g., create, retrieve)
        if self.action in ['create', 'retrieve']:
            return UserSerializer
        return self.serializer_class

class ClubViewSet(viewsets.ModelViewSet):
    queryset = Club.objects.all()
    serializer_class = ClubSerializer
    permission_classes = [IsClubOwner] # Clubs are public whereas the other requests are only for logged users

    def perform_create(self, serializer):
        serializer.save(creator=self.request.user)

class TournamentViewSet(viewsets.ModelViewSet):
    queryset = Tournament.objects.all()
    serializer_class = TournamentSerializer

    def get_queryset(self):
        if self.request.user.is_anonymous:
            return []
        return self.queryset.filter(event__creator=self.request.user)

class PurchaseViewSet(viewsets.ModelViewSet):
    queryset = Purchase.objects.all()
    serializer_class = PurchaseSerializer

    def get_queryset(self):
        if self.request.user:
            return self.queryset.filter(user=self.request.user)
        return []

    def put(self, request, pk):
        raise MethodNotAllowed('PUT')

    def patch(self, request, pk):
        raise MethodNotAllowed('PATCH')

    def delete(self, request, pk):
        raise MethodNotAllowed('DELETE')

# class ExpandedTournamentViewSet(viewsets.ModelViewSet):
#     queryset = Tournament.objects.all()
#     serializer_class = ExpandedTournamentSerializer

class ChangePasswordView(UpdateAPIView):
    serializer_class = ChangePasswordSerializer

    def update(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()
        # if using drf authtoken, create a new token
        if hasattr(user, 'auth_token'):
            user.auth_token.delete()
        token, created = Token.objects.get_or_create(user=user)
        # return new token
        return Response({'token': token.key}, status=status.HTTP_200_OK)

class EventViewSet(viewsets.ModelViewSet):
    queryset = Event.objects.all()
    serializer_class = EventSerializer

    def get_queryset(self):
        if self.request.user.is_anonymous:
            return []
        return self.queryset.filter(creator=self.request.user)

class RoundViewSet(viewsets.ModelViewSet):
    queryset = Round.objects.all()
    serializer_class = RoundSerializer

    def get_queryset(self):
        tournament_id = self.request.query_params.get('tournament')
        if tournament_id:
            return self.queryset.filter(tournament=tournament_id)
        if self.request.user:
            return self.queryset.filter(tournament__event__creator=self.request.user)
        return []

class GroupStageViewSet(viewsets.ModelViewSet):
    queryset = GroupStage.objects.all()
    serializer_class = GroupStageSerializer

    def get_queryset(self):
        tournament_id = self.request.query_params.get('tournament')
        if tournament_id:
            return self.queryset.filter(tournament=tournament_id)
        if self.request.user:
            return self.queryset.filter(tournament__event__creator=self.request.user)
        return []

class MatchViewSet(viewsets.ModelViewSet):
    queryset = Match.objects.all()
    serializer_class = MatchSerializer

    def get_queryset(self):
        tournament_id = self.request.query_params.get('tournament')
        if tournament_id:
            return self.queryset.filter(Q(group_stage__tournament=tournament_id) | Q(round__tournament=tournament_id))
        if self.request.user:
            return self.queryset.filter(Q(group_stage__tournament__event__creator=self.request.user) | Q(round__tournament__event__creator=self.request.user))
        return []

class TeamScoreViewSet(viewsets.ModelViewSet):
    queryset = TeamScore.objects.all()
    serializer_class = TeamScoreSerializer

    def get_queryset(self):
        tournament_id = self.request.query_params.get('tournament')
        if tournament_id:
            return self.queryset.filter(team_registration__tournament=tournament_id)
        if self.request.user:
            return self.queryset.filter(team_registration__tournament__event__creator=self.request.user)
        return []

class TeamRegistrationViewSet(viewsets.ModelViewSet):
    queryset = TeamRegistration.objects.all()
    serializer_class = TeamRegistrationSerializer

    def get_queryset(self):
        tournament_id = self.request.query_params.get('tournament')
        if tournament_id:
            return self.queryset.filter(tournament=tournament_id)
        if self.request.user:
            return self.queryset.filter(tournament__event__creator=self.request.user)
        return []

class PlayerRegistrationViewSet(viewsets.ModelViewSet):
    queryset = PlayerRegistration.objects.all()
    serializer_class = PlayerRegistrationSerializer

    def get_queryset(self):
        tournament_id = self.request.query_params.get('tournament')
        if tournament_id:
            return self.queryset.filter(team_registration__tournament=tournament_id)
        if self.request.user:
            return self.queryset.filter(team_registration__tournament__event__creator=self.request.user)
        return []

class CourtViewSet(viewsets.ModelViewSet):
    queryset = Court.objects.all()
    serializer_class = CourtSerializer

class DateIntervalViewSet(viewsets.ModelViewSet):
    queryset = DateInterval.objects.all()
    serializer_class = DateIntervalSerializer

    def get_queryset(self):
        if self.request.user:
            return self.queryset.filter(event__creator=self.request.user)
        return []

class FailedApiCallViewSet(viewsets.ModelViewSet):
    queryset = FailedApiCall.objects.all()
    serializer_class = FailedApiCallSerializer
    permission_classes = [] # FailedApiCall are public whereas the other requests are only for logged users

    def get_queryset(self):
        return []

    def perform_create(self, serializer):
        if self.request.user.is_anonymous == False:
            serializer.save(user=self.request.user)
        else:
            serializer.save()

class LogViewSet(viewsets.ModelViewSet):
    queryset = Log.objects.all()
    serializer_class = LogSerializer
    permission_classes = [] # Log are public whereas the other requests are only for logged users

    def get_queryset(self):
        return []

    def perform_create(self, serializer):
        if self.request.user.is_anonymous == False:
            serializer.save(user=self.request.user)
        else:
            serializer.save()

class DeviceTokenViewSet(viewsets.ModelViewSet):
    queryset = DeviceToken.objects.all()
    serializer_class = DeviceTokenSerializer

    def get_queryset(self):
        if self.request.user:
            return self.queryset.filter(user=self.request.user)
        return []

    def create(self, request, *args, **kwargs):
        value = request.data.get('value')
        if DeviceToken.objects.filter(value=value).exists():
            return Response({"detail": "This device token is already registered."}, status=208)

        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)
