from rest_framework import viewsets
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

from .models import TournamentModel
from .serializers import TournamentSerializer

# Create your views here.
class TournamentViewSet(viewsets.ModelViewSet):
    
	queryset = TournamentModel.objects.all
	serializer_class = TournamentSerializer
	permission_classes = (permissions.IsAuthenticated,)
	authentication_classes = (SessionAuthentication,)

	def perform_create(self, serializer: TournamentSerializer):

		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

		tournament = serializer.save(level = level)
		
		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):

		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)