import mimetypes
from django.db import models


def get_upload_to(instance, filename, folder):
    return f"{folder}/{instance.hash_blake3[:2]}/{instance.hash_blake3[2:4]}/{filename}"


def get_upload_to_posts(instance, filename):
    return get_upload_to(instance, filename, "posts")


def get_upload_to_thumbnails(instance, filename):
    return get_upload_to(instance, filename, "thumbnails")


class FileNameModel(models.Model):
    filename = models.CharField(max_length=512)

    date_created = models.DateTimeField(auto_now_add=True)
    date_modified = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = "File Name"
        verbose_name_plural = "File Names"

    def __str__(self):
        return str(self.filename)


class PostFileModel(models.Model):
    name = models.ManyToManyField(to=FileNameModel, related_name="post_files")
    file = models.FileField(upload_to=get_upload_to_posts, blank=True)
    # Hash for file identification (blake3 is used for deduplication)
    hash_blake3 = models.CharField(max_length=128)
    hash_md5 = models.CharField(max_length=32)
    hash_sha1 = models.CharField(max_length=40)
    hash_sha256 = models.CharField(max_length=64)
    hash_sha512 = models.CharField(max_length=128)

    # Image Blur Hash for preview presentation
    blur_hash = models.CharField(max_length=32)
    # If file has width and hight save it.
    hight = models.IntegerField(null=True)
    width = models.IntegerField(null=True)

    mimetype = models.CharField(max_length=256, blank=True)
    file_type = models.CharField(max_length=16, blank=True)

    extension = models.CharField(max_length=64, blank=True)

    manual_added = models.BooleanField(default=False)

    # Thumbnails for video file and others
    thumbnail = models.FileField(upload_to=get_upload_to_thumbnails, blank=True)
    thumbnail_hash_blake3 = models.CharField(max_length=128, blank=True)
    thumbnail_blur_hash = models.CharField(max_length=64, blank=True)

    class Meta:
        verbose_name = "Post File"
        verbose_name_plural = "Post Files"

    def __str__(self):
        return str(self.name.first())