from rest_framework.views import APIView
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 django.core import serializers


from .models import ChatChannelModel, ChatMemberModel, ChatMessageModel
from .serializers import ChatChannelSerializer, ChatMessageSerializer

class ChannelView(APIView):
    
	queryset = ChatChannelModel.objects
	serializer_class = ChatChannelSerializer
	permission_classes = (permissions.IsAuthenticated,)
	authentication_classes = (SessionAuthentication,)	

	def post(self, request):

		serializer = self.serializer_class(data = request.data)
		
		serializer.is_valid(raise_exception=True)

		data: dict = serializer.validated_data

		members_id = data.get("members_id")
		if members_id == None:
			return Response({"detail": "members_id is None."}, status = status.HTTP_400_BAD_REQUEST)

		if self.request.user.pk not in members_id:
			return Response({"detail": "You are trying to create a chat group without you."}, status = status.HTTP_400_BAD_REQUEST)

		for member_channel in ChatMemberModel.objects.filter(member_id = members_id[0]):
			channel_id: int = member_channel.channel_id
			if not ChatChannelModel.objects.filter(pk = channel_id).exists():
				continue
			channel: ChatChannelModel = ChatChannelModel.objects.get(pk = channel_id)
			if set(channel.get_members_id()) == set(members_id):
				messages = ChatMessageModel.objects.filter(channel_id = channel_id).order_by("time")
				messages = serializers.serialize("json", messages)
				return Response({'channel_id': channel_id, 'messages': messages}, status=status.HTTP_200_OK)				

		new_channel_id = ChatChannelModel().create(members_id)
		return Response({'channel_id': new_channel_id}, status=status.HTTP_201_CREATED)
