# Path: restapi/serializers.py
# class UserSerializer(serializers.HyperlinkedModelSerializer):
#     class Meta:
#         model = User
#         fields = ('id', 'username')
# 
# class ChatSerializer(serializers.ModelSerializer):
#     last_message = serializers.ReadOnlyField(source='last_message_text')
#     last_message_sender_id = serializers.ReadOnlyField()
#     last_message_timestamp = serializers.ReadOnlyField()
#     last_message_is_read = serializers.ReadOnlyField()
#     interlocutor_id = serializers.SerializerMethodField()
#     interlocutor_username = serializers.SerializerMethodField()
#     is_interlocutor_typing = serializers.SerializerMethodField()
# 
#     def get_interlocutor_id(self, chat):
#         interlocutor = chat.participants.exclude(id=self.context['request'].user.id).first()
#         return interlocutor.id
# 
#     def get_interlocutor_username(self, chat):
#         interlocutor = chat.participants.exclude(id=self.context['request'].user.id).first()
#         return interlocutor.username
# 
#     def get_is_interlocutor_typing(self, chat):
#         return False
# 
#     class Meta:
#         model = Chat
#         fields = ('id', 'last_message', 'last_message_sender_id',
#                   'last_message_timestamp', 'last_message_is_read', 'interlocutor_id',
#                   'interlocutor_username', 'is_interlocutor_typing')
# 
# class MessageSerializer(serializers.ModelSerializer):
#     sender_username = serializers.ReadOnlyField()
# 
#     class Meta:
#         model = Message
#         fields = ('text', 'sender_username', 'timestamp', 'is_read')
# 
# Path: chat/models.py
# class Chat(models.Model):
#     id = models.AutoField(primary_key=True, editable=False)
#     participants = models.ManyToManyField(User)
#     messages = models.ManyToManyField(Message)
#     timestamp = models.DateTimeField(auto_now_add=True)
# 
#     @property
#     def last_message_text(self):
#         return self.messages.latest('timestamp').text
# 
#     @property
#     def last_message_sender_id(self):
#         return self.messages.latest('timestamp').sender.id
# 
#     @property
#     def last_message_timestamp(self):
#         return self.messages.latest('timestamp').timestamp
# 
#     @property
#     def last_message_is_read(self):
#         return self.messages.latest('timestamp').is_read
# 
#     def __str__(self):
#         return str(self.id)
# 
#     class Meta:
#         verbose_name = 'Chat'
#         ordering = ['-timestamp']
# 
# class Message(models.Model):
#     text = models.CharField(max_length=3000)
#     sender = models.ForeignKey(User)
#     timestamp = models.DateTimeField(auto_now_add=True)
#     is_read = models.BooleanField(default=False)
# 
#     @property
#     def sender_username(self):
#         return self.sender.username
# 
#     def __str__(self):
#         return self.text
# 
#     class Meta:
#         verbose_name = 'Message'
#         ordering = ['-timestamp']
# 
# Path: chat/constants.py
# MESSAGES_PAGE_SIZE = 50
# CHAT_ALREADY_EXISTS = 'CHAT_ALREADY_EXISTS';
# CHAT_NEW = 'CHAT_NEW'
# SEND_MESSAGE = 'SEND_MESSAGE'
# READ_MESSAGE = 'READ_MESSAGE'
# IS_USER_TYPING = 'IS_USER_TYPING'
# DISPLAY_CHAT_ON_RECIPIENT_SIDE = 'DISPLAY_CHAT_ON_RECIPIENT_SIDE'


from django.contrib.auth.models import User
from django.shortcuts import render
from django.core.paginator import Paginator
from rest_framework.response import Response
from rest_framework import viewsets, status, permissions
from rest_framework.decorators import api_view
from restapi.serializers import UserSerializer, ChatSerializer, MessageSerializer
from chat.models import Chat, Message
from chat import constants
import json
    users = User.objects.all().exclude(username=request.user).order_by('date_joined')
    serializer = UserSerializer(users, many=True)
    return Response(serializer.data)


@api_view(['GET'])
def get_user_chats(request):
    if not request.user.is_authenticated():
        return Response('You are not logged in', status=status.HTTP_400_BAD_REQUEST)

    user_chats = Chat.objects.filter(participants=request.user)
    serializer = ChatSerializer(user_chats, context={'request': request}, many=True)
    return Response(serializer.data)


@api_view(['POST'])
def create_chat(request):
    if not request.user.is_authenticated():
        return Response('You are not logged in', status=status.HTTP_400_BAD_REQUEST)

    data = request.data
    username = data['username']

    recipient = User.objects.get(username=username)

    chat = Chat.objects.filter(participants=recipient).filter(participants=request.user)
    if chat.exists():
        chat = chat.first()
        return Response({'type': constants.CHAT_ALREADY_EXISTS, 'chat_id': chat.id})


# Path: restapi/serializers.py
# class UserSerializer(serializers.HyperlinkedModelSerializer):
#     class Meta:
#         model = User
#         fields = ('id', 'username')
# 
# class ChatSerializer(serializers.ModelSerializer):
#     last_message = serializers.ReadOnlyField(source='last_message_text')
#     last_message_sender_id = serializers.ReadOnlyField()
#     last_message_timestamp = serializers.ReadOnlyField()
#     last_message_is_read = serializers.ReadOnlyField()
#     interlocutor_id = serializers.SerializerMethodField()
#     interlocutor_username = serializers.SerializerMethodField()
#     is_interlocutor_typing = serializers.SerializerMethodField()
# 
#     def get_interlocutor_id(self, chat):
#         interlocutor = chat.participants.exclude(id=self.context['request'].user.id).first()
#         return interlocutor.id
# 
#     def get_interlocutor_username(self, chat):
#         interlocutor = chat.participants.exclude(id=self.context['request'].user.id).first()
#         return interlocutor.username
# 
#     def get_is_interlocutor_typing(self, chat):
#         return False
# 
#     class Meta:
#         model = Chat
#         fields = ('id', 'last_message', 'last_message_sender_id',
#                   'last_message_timestamp', 'last_message_is_read', 'interlocutor_id',
#                   'interlocutor_username', 'is_interlocutor_typing')
# 
# class MessageSerializer(serializers.ModelSerializer):
#     sender_username = serializers.ReadOnlyField()
# 
#     class Meta:
#         model = Message
#         fields = ('text', 'sender_username', 'timestamp', 'is_read')
# 
# Path: chat/models.py
# class Chat(models.Model):
#     id = models.AutoField(primary_key=True, editable=False)
#     participants = models.ManyToManyField(User)
#     messages = models.ManyToManyField(Message)
#     timestamp = models.DateTimeField(auto_now_add=True)
# 
#     @property
#     def last_message_text(self):
#         return self.messages.latest('timestamp').text
# 
#     @property
#     def last_message_sender_id(self):
#         return self.messages.latest('timestamp').sender.id
# 
#     @property
#     def last_message_timestamp(self):
#         return self.messages.latest('timestamp').timestamp
# 
#     @property
#     def last_message_is_read(self):
#         return self.messages.latest('timestamp').is_read
# 
#     def __str__(self):
#         return str(self.id)
# 
#     class Meta:
#         verbose_name = 'Chat'
#         ordering = ['-timestamp']
# 
# class Message(models.Model):
#     text = models.CharField(max_length=3000)
#     sender = models.ForeignKey(User)
#     timestamp = models.DateTimeField(auto_now_add=True)
#     is_read = models.BooleanField(default=False)
# 
#     @property
#     def sender_username(self):
#         return self.sender.username
# 
#     def __str__(self):
#         return self.text
# 
#     class Meta:
#         verbose_name = 'Message'
#         ordering = ['-timestamp']
# 
# Path: chat/constants.py
# MESSAGES_PAGE_SIZE = 50
# CHAT_ALREADY_EXISTS = 'CHAT_ALREADY_EXISTS';
# CHAT_NEW = 'CHAT_NEW'
# SEND_MESSAGE = 'SEND_MESSAGE'
# READ_MESSAGE = 'READ_MESSAGE'
# IS_USER_TYPING = 'IS_USER_TYPING'
# DISPLAY_CHAT_ON_RECIPIENT_SIDE = 'DISPLAY_CHAT_ON_RECIPIENT_SIDE'


# Path: restapi/views.py
from django.contrib.auth.models import User
from django.shortcuts import render
from django.core.paginator import Paginator
from rest_framework.response import Response
from rest_framework import viewsets, status, permissions
from rest_framework.decorators import api_view
from restapi.serializers import UserSerializer, ChatSerializer, MessageSerializer
from chat.models import Chat, Message
from chat import constants
import json

    users = User.objects.all().exclude(username=request.user).order_by('date_joined')
    serializer = UserSerializer(users, many=True)
    return Response(serializer.data)


@api_view(['GET'])
def get_user_chats(request):
    if not request.user.is_authenticated():
        return Response('You are not logged in', status=status.HTTP_400_BAD_REQUEST)

    user_chats = Chat.objects.filter(participants=request.user)
    serializer = ChatSerializer(user_chats, context={'request': request}, many=True)
    return Response(serializer.data)


@api_view(['POST'])
def create_chat(request):
    if not request.user.is_authenticated():
        return Response('You are not logged in', status=status.HTTP_400_BAD_REQUEST)

    data = request.data
    username = data['username']

    recipient = User.objects.get(username=username)

    chat = Chat.objects.filter(participants=recipient).filter(participants=request.user)
    if chat.exists():
        chat = chat.first()
        return Response({'type': constants.CHAT_ALREADY_EXISTS, 'chat_id': chat.id})


    chat = Chat.objects.create()