2023-12-20 15:09:31 -05:00
|
|
|
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
|
2023-12-20 15:09:31 -05:00
|
|
|
from django.db.models import QuerySet
|
2023-12-20 13:15:47 -05:00
|
|
|
|
|
|
|
from matchmaking.models import in_matchmaking
|
|
|
|
from .models import TournamentModel
|
2023-12-20 15:09:31 -05:00
|
|
|
from .serializers import TournamentSerializer
|
2023-12-20 13:15:47 -05:00
|
|
|
|
|
|
|
# Create your views here.
|
2023-12-20 15:09:31 -05:00
|
|
|
class TournamentViewSet(viewsets.ModelViewSet):
|
2023-12-20 13:15:47 -05:00
|
|
|
|
2023-12-20 15:09:31 -05:00
|
|
|
queryset = TournamentModel.objects.all
|
|
|
|
serializer_class = TournamentSerializer
|
2023-12-20 13:15:47 -05:00
|
|
|
permission_classes = (permissions.IsAuthenticated,)
|
|
|
|
authentication_classes = (SessionAuthentication,)
|
|
|
|
|
2023-12-20 15:58:52 -05:00
|
|
|
def perform_create(self, serializer: TournamentSerializer):
|
2023-12-20 13:15:47 -05:00
|
|
|
|
2023-12-20 15:58:52 -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
|
|
|
|
2023-12-20 15:58:52 -05:00
|
|
|
tournament = serializer.save(level = level)
|
2023-12-20 13:15:47 -05:00
|
|
|
|
2023-12-20 15:58:52 -05:00
|
|
|
return Response(self.serializer_class(tournament).data, status=status.HTTP_201_CREATED)
|
2023-12-20 15:09:31 -05:00
|
|
|
|
|
|
|
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)
|
2023-12-20 15:58:52 -05:00
|
|
|
case "waiting":
|
2023-12-20 15:09:31 -05:00
|
|
|
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)
|
|
|
|
|
2023-12-20 15:09:31 -05:00
|
|
|
return Response(self.serializer_class(tournament).data, status=status.HTTP_200_OK)
|