from django.db import models
from BaseModels.base_models import BaseModel
from django.utils.translation import gettext_lazy as _

msg_type_choices = (
    ('support', _('техподдержка')),
    ('private', _('личное'))
)

msg_status_choices = (
    ('sended', _('Отправлено')),
    ('seen', _('Просмотрено'))
)

grp_msg_status = (
    ('open', _('Открыт')),
    ('answered', _('Отвечен')),
    ('closed', _('Закрыт'))
)


grp_msg_department = (
    ('support', _('Отдел: Техническая поддержка')),
    ('finance', _('Отдел: Финансовый департамент')),
)


class MsgGroup(BaseModel):
    from AuthApp.models import User

    department = models.CharField(verbose_name=_('Отдел'), default='support', choices=grp_msg_department)
    status = models.CharField(verbose_name=_('Статус'), default='open', choices=grp_msg_status)

    text = models.TextField(verbose_name=_('Сообщение'))

    owner = models.ForeignKey(User, verbose_name=_('Владелец'), related_name='rel_msgGroups_for_owner',
                              on_delete=models.SET_NULL, null=True)
    manager = models.ForeignKey(User, verbose_name=_('Менеджер'), related_name='rel_msgGroups_for_manager',
                              on_delete=models.SET_NULL, null=True)

    def get_last_msg_txt(self):
        msg = self.rel_messages_for_group.all().order_by('-createDT').first()
        if not msg:
            return self.text

        if msg.text:
            return msg.text
        elif msg.files:
            return msg.files[0].file_name

        return self.name

    class Meta:
        verbose_name = _('Тикет')
        verbose_name_plural = _('Тикеты')


class Message(BaseModel):
    from AuthApp.models import User

    msg_type = models.CharField(max_length=50, verbose_name=_('Тип сообщения'), default='private', choices=msg_type_choices)
    group = models.ForeignKey(
        MsgGroup, verbose_name=_('Группа сообщений'), related_name='rel_messages_for_group',
        on_delete=models.SET_NULL, null=True)

    sender = models.ForeignKey(
        User, verbose_name=_('Отправитель'), on_delete=models.CASCADE, related_name='rel_messages_for_sender'
    )
    receiver = models.ForeignKey(
        User, verbose_name=_('Получатель'), on_delete=models.CASCADE, related_name='rel_messages_for_receiver'
    )

    text = models.TextField(verbose_name=_('Сообщение'))

    status = models.CharField(verbose_name=_('Статус'), default='sended', choices=msg_status_choices)

    files = models.JSONField(verbose_name=_('Прикрепленные файлы'), default=dict)

    class Meta:
        verbose_name = _('Сообщение')
        verbose_name_plural = _('Сообщения')

