from django.db import models
from osinacore.models import *
import mimetypes
import os
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
import json

# Create your models here.

class Visitor(models.Model):
    session_id = models.CharField(max_length=300)
    ip_address = models.CharField(max_length=300)
    country = models.CharField(max_length=15, null=True)
    name = models.CharField(max_length=200, blank=True, null=True)
    mobile_number = models.CharField(max_length=10, null=True, blank=True)
    email = models.CharField(max_length=100, null=True, blank=True)
    @property
    def flag_image_url(self):
        flag_url =  f"https://flagcdn.com/w320/{self.country.lower()}.webp"
        return flag_url



class VisitorLog(models.Model):
    visitor = models.ForeignKey(Visitor, on_delete=models.CASCADE, null=True)
    url = models.URLField()
    referrer = models.URLField(null=True, blank=True)
    visit_date = models.DateTimeField(null=True)
    left_date = models.DateTimeField(null=True)


class ChatRoom(models.Model):
    name = models.CharField(max_length=300)
    created_by = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, blank=True)
    date_created = models.DateTimeField()
    terminated_by = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, blank=True,  related_name='terminated_chatrooms')
    date_terminated = models.DateTimeField(null=True, blank=True)
    @property
    def last_updated(self):
        last_message = ChatMessage.objects.filter(room=self).order_by('-date_sent').first()
        if last_message:
            last_updated_time = last_message.date_sent
        else:
            last_updated_time = self.date_created

        now = datetime.now()
        if last_updated_time.date() == now.date():
            return last_updated_time.strftime('%I:%M %p')
        else:
            return last_updated_time.strftime('%d-%m-%Y')
    def unread_messages(self, user):
        return ChatMessage.objects.filter(room=self).exclude(member=user).exclude(chatmessageseen__member=user).count()
    

    def save(self, *args, **kwargs):
        is_new = self.pk is None 
        super().save(*args, **kwargs)
        channel_layer = get_channel_layer()
        event = {
            'type': 'new_update_handler',
            'chatroom_id': self.id,
        }
        async_to_sync(channel_layer.group_send)("ositcom_chats", event)



class ChatRoomGuest(models.Model):
    room = models.OneToOneField(ChatRoom, on_delete=models.CASCADE, null=True)
    visitor = models.ForeignKey(Visitor, null=True, on_delete=models.CASCADE)


class ChatRoomReview(models.Model):
    REACTION_CHOICES = (
        ('Happy', 'Happy'),
        ('Indifferent', 'Indifferent'),
        ('Sad', 'Sad'),
    )
    room = models.OneToOneField(ChatRoom, on_delete=models.CASCADE, null=True)
    reaction =  models.CharField(max_length=50, choices=REACTION_CHOICES, null=True)
    details = models.TextField(null=True, blank=True)

class ChatMember(models.Model):
    member = models.ForeignKey(User, on_delete=models.CASCADE)
    room = models.ForeignKey(ChatRoom, on_delete=models.CASCADE)
    date_joined = models.DateTimeField()


class ChatProject(models.Model):
    room = models.OneToOneField(ChatRoom, on_delete=models.CASCADE)
    project = models.ForeignKey(Project, on_delete=models.CASCADE)
    public = models.BooleanField()


class ChatMessage(models.Model):
    room = models.ForeignKey(ChatRoom, on_delete=models.CASCADE, null=True)
    member = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, blank=True)
    content = models.TextField(null=True, blank=True)
    date_sent = models.DateTimeField()
    def save(self, *args, **kwargs):
        is_new = self.pk is None 
        super().save(*args, **kwargs)
        channel_layer = get_channel_layer()
        event = {
            'type': 'new_update_handler',
            'chatroom_id': self.room.id,
        }
        async_to_sync(channel_layer.group_send)("ositcom_chats", event)


class ChatMessageAttachment(models.Model):
    message = models.OneToOneField(ChatMessage, on_delete=models.CASCADE)
    attachment = models.TextField()
    def is_image(self):
        mime_type, _ = mimetypes.guess_type(self.attachment)
        return mime_type and mime_type.startswith('image')
    @property
    def file_name(self):
        return os.path.basename(self.attachment)


class ChatMessageReaction(models.Model):
    message = models.ForeignKey(ChatMessage, on_delete=models.CASCADE)
    member = models.ForeignKey(User, on_delete=models.CASCADE)
    reaction = models.CharField(max_length=200)


class ChatMessageSeen(models.Model):
    message = models.ForeignKey(ChatMessage, on_delete=models.CASCADE)
    member = models.ForeignKey(User, on_delete=models.CASCADE,  null=True, blank=True)
    guest = models.ForeignKey(ChatRoomGuest, on_delete=models.CASCADE, null=True, blank=True)
    seen_date = models.DateTimeField(null=True)