import os

from django.db import models
from django.conf import settings

from tickets.models.ticket import Ticket


def get_attachment_upload_dir(instance, filename):
    """Determine upload dir for ticket attachment files."""

    return "/".join(["attachments", str(instance.ticket.id), filename])


class Attachment(models.Model):
    """
    Defines a generic file attachment for use in M2M relation with ticket.
    """

    ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE)
    added_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    timestamp = models.DateTimeField(auto_now_add=True)
    file = models.FileField(upload_to=get_attachment_upload_dir, max_length=255)

    def filename(self):
        return os.path.basename(self.file.name)

    def extension(self):
        name, extension = os.path.splitext(self.file.name)
        return extension

    def __str__(self):
        return f"{self.ticket.id} - {self.file.name}"