# Path: chat/models.py
# 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']
# 
# 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']
# 
# Path: chat/utils.py
# def json_response(obj):
#     response = HttpResponse(json.dumps(obj, default=date_handler), content_type='application/json')
# 
#     # TODO remove this in production
#     response['Access-Control-Allow-Origin'] = '*'
#     response['Access-Control-Allow-Methods'] = 'POST, GET'
#     response['Access-Control-Allow-Headers'] = '*'
# 
#     return response
# 
# def date_handler(obj):
#     if hasattr(obj, 'isoformat'):
#         return obj.isoformat()
#     else:
#         raise TypeError
# 
# 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.shortcuts import render, redirect, HttpResponse
from django.contrib.auth.models import User
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
from chat.models import Message, Chat
from chat.utils import json_response, date_handler
from chat import constants
import json
import time
    if api_key != settings.API_KEY:
        return json_response({'error': 'API key is incorrect.'})



    sender_id = request.POST.get('sender_id')
    chat_id = request.POST.get('chat_id')
    message_text = request.POST.get('message')

    chat = Chat.objects.get(id=chat_id)
    sender = User.objects.get(id=sender_id)

    if not chat.participants.filter(id=sender_id).exists():
        return HttpResponse('You are not belong to this conversation')

    message_instance = Message()
    message_instance.sender = sender
    message_instance.text = message_text
    message_instance.save()

    chat.messages.add(message_instance)

    return json_response({'status': 'ok'})


@csrf_exempt
def read_chat_message_api(request):
    api_key = request.POST.get('api_key')

    if api_key != settings.API_KEY:

# Path: chat/models.py
# 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']
# 
# 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']
# 
# Path: chat/utils.py
# def json_response(obj):
#     response = HttpResponse(json.dumps(obj, default=date_handler), content_type='application/json')
# 
#     # TODO remove this in production
#     response['Access-Control-Allow-Origin'] = '*'
#     response['Access-Control-Allow-Methods'] = 'POST, GET'
#     response['Access-Control-Allow-Headers'] = '*'
# 
#     return response
# 
# def date_handler(obj):
#     if hasattr(obj, 'isoformat'):
#         return obj.isoformat()
#     else:
#         raise TypeError
# 
# 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: chat/views.py
from django.shortcuts import render, redirect, HttpResponse
from django.contrib.auth.models import User
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
from chat.models import Message, Chat
from chat.utils import json_response, date_handler
from chat import constants
import json
import time

    if api_key != settings.API_KEY:
        return json_response({'error': 'API key is incorrect.'})



    sender_id = request.POST.get('sender_id')
    chat_id = request.POST.get('chat_id')
    message_text = request.POST.get('message')

    chat = Chat.objects.get(id=chat_id)
    sender = User.objects.get(id=sender_id)

    if not chat.participants.filter(id=sender_id).exists():
        return HttpResponse('You are not belong to this conversation')

    message_instance = Message()
    message_instance.sender = sender
    message_instance.text = message_text
    message_instance.save()

    chat.messages.add(message_instance)

    return json_response({'status': 'ok'})


@csrf_exempt
def read_chat_message_api(request):
    api_key = request.POST.get('api_key')

    if api_key != settings.API_KEY:

        return json_response({'error': 'API key is incorrect.'})