ft_transcendence/tournament/viewset.py

56 lines
1.9 KiB
Python
Raw Normal View History

from rest_framework import viewsets
2023-12-20 13:15:47 -05:00
from rest_framework.response import Response
from rest_framework import permissions, status
from rest_framework.authentication import SessionAuthentication
from django.http import HttpRequest
from django.contrib.auth import login
from django.db.models import QuerySet
2023-12-20 13:15:47 -05:00
from .models import TournamentModel
from .serializers import TournamentSerializer
2023-12-20 13:15:47 -05:00
# Create your views here.
class TournamentViewSet(viewsets.ModelViewSet):
2023-12-20 13:15:47 -05:00
queryset = TournamentModel.objects.all
serializer_class = TournamentSerializer
2023-12-20 13:15:47 -05:00
permission_classes = (permissions.IsAuthenticated,)
authentication_classes = (SessionAuthentication,)
def perform_create(self, serializer: TournamentSerializer):
2023-12-20 13:15:47 -05:00
nb_players = serializer.validated_data["nb_players"]
nb_players_by_game = serializer.validated_data["nb_players_by_game"]
level = 1
number: int = nb_players
while (number != nb_players_by_game):
number = number // 2 + (number % 2)
level += 1
2023-12-20 13:15:47 -05:00
tournament = serializer.save(level = level)
2023-12-20 13:15:47 -05:00
return Response(self.serializer_class(tournament).data, status=status.HTTP_201_CREATED)
def list(self, request: HttpRequest, state: str = ""):
query: QuerySet
match state:
case "started":
query = TournamentModel.objects.filter(started=True, finished=False)
case "finished":
query = TournamentModel.objects.filter(finished=True)
case "waiting":
query = TournamentModel.objects.filter(started=False, finished=False)
case _:
query = TournamentModel.objects.all()
serializer = TournamentSerializer(query, many=True)
return Response(serializer.data)
def retrieve(self, request: HttpRequest, pk):
2023-12-20 13:15:47 -05:00
if (not TournamentModel.objects.filter(pk=pk).exists()):
return Response({"detail": "Tournament not found."}, status=status.HTTP_404_NOT_FOUND)
tournament = TournamentModel.objects.get(pk=pk)
return Response(self.serializer_class(tournament).data, status=status.HTTP_200_OK)