# -*- encoding: utf-8 -*-

import uuid
import bleach
from datetime import timedelta, datetime

from django.db import models
from django.conf import settings
from django.utils import timezone
from django.utils.translation import gettext_lazy as _


class TicketPriority(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

    title = models.CharField(max_length=32)
    colour = models.CharField(max_length=7)

    def __str__(self):
        return self.title

    def serialize(self) -> dict:
        return {
            "id": self.id,
            "title": self.title,
            "colour": self.colour
        }


class TicketTag(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

    title = models.CharField(max_length=32)
    colour = models.CharField(max_length=7)

    def __str__(self):
        return self.title

    def serialize(self) -> dict:
        return {
            "id": self.id,
            "title": self.title,
            "colour": self.colour
        }


class Ticket(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

    title = models.CharField(
        _("title"),
        max_length=100,
        help_text=_("An extremely short summary of the ticket subject.")
    )
    description = models.TextField(
        _("description"),
        max_length=650,
        help_text=_("Detailed description of the ticket subject.")
    )
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        verbose_name=_("author"),
        on_delete=models.CASCADE,
        help_text=_("The creator of the ticket.")
    )

    priority = models.ForeignKey(
        TicketPriority,
        verbose_name=_("priority"),
        on_delete=models.CASCADE,
        help_text=_("The importance level of this ticket.")
    )
    tags = models.ManyToManyField(
        TicketTag,
        verbose_name=_("tags"),
        blank=True,
        help_text=_("Categories of the ticket.")
        
    )

    create_timestamp = models.DateTimeField(
        _("Creation Date"),
        editable=True,
        default=timezone.now,
        help_text=_("When the user was created.")
    )
    edit_timestamp = models.DateTimeField(
        _("Last Edited"),
        editable=True,
        default=timezone.now,
        help_text=_("When the user was last edited.")
    )

    def __str__(self):
        return f"#{self.id} • {self.title} •{f' {self.author.department.title} •' if self.author.department else ''} {self.author.formal_fullname}"

    def clean_description(self):
        cleaned_description = bleach.clean(
            self.description,
            tags=['b', 'i', 'u', 'p', 'br', 'a', 'h3', 'h4', 'h5', 'h6'],
            attributes={'a': ['href', 'title']}
        )
        return cleaned_description

    def save(self, *args, **kwargs):
        self.description = self.clean_description()
        self.edit_timestamp = timezone.now()
        super().save(*args, **kwargs)

    @property
    def is_edited(self) -> bool:
        """Returns boolean if the ticket is believed to have been edited.
        We assume a ticket is edited if the edit_timestamp doesn't match the create_timestamp.

        Returns
        -------
        bool
            True if `self.edit_timestamp` doesn't match `self.create_timestamp`, False otherwise.
        """

        return self.create_timestamp != self.edit_timestamp

    @property
    def is_older_than_day(self) -> bool:
        """Returns boolean dependent on if `self.timestamp` is older than 24 hours.

        Returns
        -------
        bool
            True if `self.timestamp` is older than 24 hours, False otherwise.
        """

        dayago = timezone.now() - timedelta(hours=24)
        return self.timestamp <= dayago

    @property
    def timestamp(self) -> datetime:
        """Returns `self.edit_timestamp` if `self.is_edited` is True, otherwise
        returns `self.create_timestamp`.

        Returns
        -------
        datetime
            Either `self.edit_timestamp` or `self.create_timestamp`.
        """

        return self.edit_timestamp if self.is_edited else self.create_timestamp

    def serialize(self) -> dict:
        return {
            "id": self.id,
            "title": self.title,
            "description": self.description,
            "author": self.author.serialize(),
            "create_timestamp": self.create_timestamp,
            "edit_timestamp": self.edit_timestamp,
            "is_edited": self.is_edited,
            "is_older_than_day": self.is_older_than_day,
            "timestamp": self.timestamp,
            "priority": self.priority.serialize(),
            "tags": [tag.serialize() for tag in self.tags.all()]
        }
