from autoslug import AutoSlugField
from django.db import models

# Create your models here.
class PostImages(models.Model):
    aktif = (
        (True, 'Evet'),
        (False, 'Hayır'),
    )
    format_choose = (
        ('png', 'PNG'),
        ('webp', 'WebP'),
        ('jpg', 'JPG'),
        ('avif', 'AVIF'),
    )
    title = models.CharField(max_length=254, verbose_name="Resim Başlığı")
    user = models.ForeignKey('accounts.CustomUser', on_delete=models.CASCADE, related_name='image_user',
                             verbose_name="Kullanıcı")
    path = models.CharField(max_length=254, verbose_name="Resim Yolu")
    processed_path = models.CharField(max_length=254, verbose_name="Orijinal Resim Yolu")
    original_filename = models.CharField(max_length=254, verbose_name="Orijinal Resim Adı")
    format = models.CharField(max_length=254, verbose_name="Resim Formati", choices=format_choose,default='webp')
    width = models.IntegerField()
    height = models.IntegerField()
    size = models.IntegerField()
    quality = models.IntegerField()

    slug = AutoSlugField(populate_from='title', null=False, unique=True, editable=True, db_index=True, max_length=250,
                         blank=True)
    created_at = models.DateTimeField(auto_now_add=True, editable=False, verbose_name="Oluşturulma Tarihi")
    updated_at = models.DateTimeField(auto_now=True, editable=False, verbose_name="Güncelleme Tarihi")
    is_active = models.BooleanField(default=True, verbose_name='Yayındamı ?', choices=aktif)
    is_front = models.BooleanField(default=True, verbose_name='Önde Görünsünmü ?', choices=aktif)

    class Meta:
        ordering = ["created_at"]
        db_table = 'images'
        verbose_name_plural = "Posts"
        verbose_name = "Post"
        unique_together = ('slug',)

    def get_slug(self):
        slug = self.title.replace('ı', "i").replace('İ', 'i')
        number = 1
        while PostImages.objects.filter(slug=slug).exists():
            slug = '{}-{}'.format(slug, number)
            number += 1
        return slug

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = self.get_slug()
        super().save(*args, **kwargs)

    def __str__(self):
        return f"Resimler:  {self.title}"