"""Models for the chat app."""

from uuid import uuid4

from django.urls import reverse
from django.utils.translation import ugettext_lazy as _
from aparnik.contrib.filefields.models import FileField
from django.db import models
from django.contrib.auth import get_user_model

User = get_user_model()


class TrackableDateModel(models.Model):
    """Abstract model to Track the creation/updated date for a model."""

    created_at = models.DateTimeField(auto_now_add=True)
    update_at = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

    @property
    def resourcetype(self):
        return self._meta.object_name


def _generate_unique_uri():
    """Generates a unique uri for the chat session."""
    return str(uuid4()).replace('-', '')[:15]

class ChatSessionManager(models.Manager):
    def get_queryset(self):
        return super(ChatSessionManager, self).get_queryset()

    def user_session(self, user):
        queryset = self.filter(
            pk__in=ChatSessionMember.objects.filter(user=user).values_list('chat_session', flat=True).distinct())
        queryset = queryset | self.filter(owner=user)
        return queryset.distinct()


class ChatSession(TrackableDateModel):
    """
    A Chat Session.

    The uri's are generated by taking the first 15 characters from a UUID
    """

    owner = models.ForeignKey(User, on_delete=models.PROTECT)
    uri = models.URLField(default=_generate_unique_uri)

    objects = ChatSessionManager()

    def __str__(self):
        return self.uri

    def get_api_uri(self):
        return reverse('aparnik-api:chats:details', args=[self.uri])

    def get_member_api_uri(self):
        return reverse('aparnik-api:chats:members', args=[self.uri])

    def get_messages_api_uri(self):
        return reverse('aparnik-api:chats:messages', args=[self.uri])

    def get_messages_create_api_uri(self):
        return reverse('aparnik-api:chats:messages-create', args=[self.uri])


class ChatSessionMessage(TrackableDateModel):
    """Store messages for a session."""

    user = models.ForeignKey(User, on_delete=models.PROTECT)
    chat_session = models.ForeignKey(
        ChatSession, related_name='messages', on_delete=models.PROTECT
    )
    message = models.TextField(default='', max_length=2000)
    file_obj= models.ForeignKey(FileField, null=True, blank=True, on_delete=models.CASCADE, verbose_name=_('File'))

    def get_api_uri(self):
        return reverse('aparnik-api:chats:messages-details', args=[self.pk])


class ChatSessionMember(TrackableDateModel):
    """Store all users in a chat session."""

    chat_session = models.ForeignKey(
        ChatSession, related_name='members', on_delete=models.PROTECT
    )
    user = models.ForeignKey(User, on_delete=models.PROTECT)

    def get_api_uri(self):
        return reverse('aparnik-api:chats:members-details', args=[self.pk])
