# Path: API/chat/utils.py
# def datetime_to_timestamp(datetime):
#     """
#     Takes a datetime and returns
#     a unix epoch ms.
#     """
#     time_without_ms = time.mktime(datetime.timetuple()) * 1000
#     ms = int(datetime.microsecond / 1000)
# 
#     return time_without_ms + ms
# 
# Path: API/chat/models.py
# class Channel(models.Model):
#     def __str__(self):
#         return self.name
# 
#     name = models.CharField(max_length=20, unique=True)
# 
# class Message(models.Model):
#     def __str__(self):
#         return self.message_content
# 
#     def to_dict(self):
#         serializable_fields = ('message_content', 'datetime_start', 'datetime_sent', 'username')
#         return {key: getattr(self, key) for key in serializable_fields}
# 
#     TEXT = 'text'
#     IMAGE = 'image'
# 
#     MESSAGE_TYPE = (
#         (TEXT, 'text'),
#         (IMAGE, 'image'),
#     )
# 
#     message_content = models.TextField(max_length=2000)
#     datetime_start = models.DateTimeField(default=None)
#     datetime_sent = models.DateTimeField(default=None, null=True)
#     typing = models.BooleanField(default=False)
#     username = models.CharField(max_length=20)
#     channel = models.ForeignKey(Channel)
#     message_type = models.CharField(max_length=10,
#                                     choices=MESSAGE_TYPE,
#                                     default=TEXT)
# 
# Path: API/chat/forms.py
# class MessageCreationForm(MessageForm):
#     username = forms.CharField(max_length=20)
#     datetime_start = forms.IntegerField()
# 
#     def clean_datetime_start(self):
#         now = int(round(time.time() * 1000))
#         timestamp = int(self.data['datetime_start'])
#         if now < timestamp:
#             timestamp = now
# 
#         self.cleaned_data['datetime_start'] = timestamp_to_datetime(timestamp)
# 
#     def save(self):
#         self.clean_datetime_start()
# 
#         message = Message.objects.create(channel=self.channel, **self.cleaned_data)
# 
#         if not message.typing:
#             message.datetime_sent = message.datetime_start
#             message.save()
# 
#         return message;
# 
# class MessagePatchForm(MessageForm):
#     datetime_sent = forms.IntegerField()
# 
#     def save(self, message):
#         timestamp_start = datetime_to_timestamp(message.datetime_start)
#         timestamp_sent = int(self.cleaned_data['datetime_sent'])
# 
#         if timestamp_sent < timestamp_start:
#             timestamp_sent = timestamp_start
# 
#         message.datetime_sent = timestamp_to_datetime(timestamp_sent)
#         message.message_content = self.cleaned_data['message_content']
#         message.typing = self.cleaned_data.get('typing', False)
# 
#         message.save()


import json
from django.shortcuts import get_object_or_404
from django.http import HttpResponse, HttpResponseBadRequest, QueryDict
from django.views.generic import View
from .utils import datetime_to_timestamp
from .models import Channel, Message
from .forms import MessageCreationForm, MessagePatchForm
from django.conf import settings
            'message_content', 'username', 'datetime_start', 'typing', 'id',
            'datetime_sent', 'message_type'
        ).filter(channel=channel).order_by('-id')[:lim]

        # convert datetime_start to UTC epoch milliseconds
        for message in messages:
            message['datetime_start'] = datetime_to_timestamp(message['datetime_start'])
            if message['datetime_sent']:
                message['datetime_sent'] = datetime_to_timestamp(message['datetime_sent'])

        messages_json = json.dumps(list(messages))

        return HttpResponse(messages_json, content_type='application/json')

    @privileged
    def delete(self, request, id, *args, **kwargs):
        message = get_object_or_404(Message, pk=id)

        message.delete()
        return HttpResponse(status=204)


class ChannelView(View):
    def post(self, request, *args, **kwargs):
        channel = Channel(name=request.POST['name'])
        channel.save()

        return HttpResponse(status=204)

    def get(self, request, *args, **kwargs):

# Path: API/chat/utils.py
# def datetime_to_timestamp(datetime):
#     """
#     Takes a datetime and returns
#     a unix epoch ms.
#     """
#     time_without_ms = time.mktime(datetime.timetuple()) * 1000
#     ms = int(datetime.microsecond / 1000)
# 
#     return time_without_ms + ms
# 
# Path: API/chat/models.py
# class Channel(models.Model):
#     def __str__(self):
#         return self.name
# 
#     name = models.CharField(max_length=20, unique=True)
# 
# class Message(models.Model):
#     def __str__(self):
#         return self.message_content
# 
#     def to_dict(self):
#         serializable_fields = ('message_content', 'datetime_start', 'datetime_sent', 'username')
#         return {key: getattr(self, key) for key in serializable_fields}
# 
#     TEXT = 'text'
#     IMAGE = 'image'
# 
#     MESSAGE_TYPE = (
#         (TEXT, 'text'),
#         (IMAGE, 'image'),
#     )
# 
#     message_content = models.TextField(max_length=2000)
#     datetime_start = models.DateTimeField(default=None)
#     datetime_sent = models.DateTimeField(default=None, null=True)
#     typing = models.BooleanField(default=False)
#     username = models.CharField(max_length=20)
#     channel = models.ForeignKey(Channel)
#     message_type = models.CharField(max_length=10,
#                                     choices=MESSAGE_TYPE,
#                                     default=TEXT)
# 
# Path: API/chat/forms.py
# class MessageCreationForm(MessageForm):
#     username = forms.CharField(max_length=20)
#     datetime_start = forms.IntegerField()
# 
#     def clean_datetime_start(self):
#         now = int(round(time.time() * 1000))
#         timestamp = int(self.data['datetime_start'])
#         if now < timestamp:
#             timestamp = now
# 
#         self.cleaned_data['datetime_start'] = timestamp_to_datetime(timestamp)
# 
#     def save(self):
#         self.clean_datetime_start()
# 
#         message = Message.objects.create(channel=self.channel, **self.cleaned_data)
# 
#         if not message.typing:
#             message.datetime_sent = message.datetime_start
#             message.save()
# 
#         return message;
# 
# class MessagePatchForm(MessageForm):
#     datetime_sent = forms.IntegerField()
# 
#     def save(self, message):
#         timestamp_start = datetime_to_timestamp(message.datetime_start)
#         timestamp_sent = int(self.cleaned_data['datetime_sent'])
# 
#         if timestamp_sent < timestamp_start:
#             timestamp_sent = timestamp_start
# 
#         message.datetime_sent = timestamp_to_datetime(timestamp_sent)
#         message.message_content = self.cleaned_data['message_content']
#         message.typing = self.cleaned_data.get('typing', False)
# 
#         message.save()


# Path: API/chat/views.py
import json
from django.shortcuts import get_object_or_404
from django.http import HttpResponse, HttpResponseBadRequest, QueryDict
from django.views.generic import View
from .utils import datetime_to_timestamp
from .models import Channel, Message
from .forms import MessageCreationForm, MessagePatchForm
from django.conf import settings

            'message_content', 'username', 'datetime_start', 'typing', 'id',
            'datetime_sent', 'message_type'
        ).filter(channel=channel).order_by('-id')[:lim]

        # convert datetime_start to UTC epoch milliseconds
        for message in messages:
            message['datetime_start'] = datetime_to_timestamp(message['datetime_start'])
            if message['datetime_sent']:
                message['datetime_sent'] = datetime_to_timestamp(message['datetime_sent'])

        messages_json = json.dumps(list(messages))

        return HttpResponse(messages_json, content_type='application/json')

    @privileged
    def delete(self, request, id, *args, **kwargs):
        message = get_object_or_404(Message, pk=id)

        message.delete()
        return HttpResponse(status=204)


class ChannelView(View):
    def post(self, request, *args, **kwargs):
        channel = Channel(name=request.POST['name'])
        channel.save()

        return HttpResponse(status=204)

    def get(self, request, *args, **kwargs):

        queryset = Channel.objects.values('name')