from autoslug import AutoSlugField
from django.db import models
from imagekit.models import ProcessedImageField

from core.utils import image_optimizer


# Create your models here.
class Category(models.Model):
    aktif = (
        (True, 'Evet'),
        (False, 'Hayır'),
    )
    title = models.CharField(max_length=254, verbose_name="Kategori")
    keywords = models.CharField(max_length=254, verbose_name="Seo Kelimeleri Aralarına Virgül Koyunuz")
    description = models.CharField(max_length=254, verbose_name="Açıklama")
    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)
    order = models.IntegerField(verbose_name='Görüntülenme Sırası', default=1, db_index=True)
    slug = AutoSlugField(populate_from='title', null=False, unique=True, editable=True, db_index=True, max_length=250,
                         blank=True)
    parent = models.ForeignKey('self', related_name='child', on_delete=models.CASCADE, blank=True, null=True,
                               verbose_name='Üst Kategorisi')
    image = ProcessedImageField(**image_optimizer('uploads/category', 300, 300, 85, 'PNG'),
                                verbose_name='Resim 630 x 653 Olmali ve Transparan PNG Olmali', blank=True, null=True)

    class Meta:
        ordering = ["order"]
        db_table = 'p_categories'
        verbose_name_plural = "Portfolio Kategorilerileri"
        verbose_name = "Portfolio Kategori"
        unique_together = ('slug', 'parent',)

    def get_slug(self):
        slug = self.title.replace('ı', "i").replace('İ', 'i')
        number = 1
        while Category.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):
        full_path = [self.title]
        k = self.parent
        while k is not None:
            full_path.append(k.title)
            k = k.parent
        return ' -> '.join(full_path[::-1])

class Portfolio(models.Model):
    aktif = (
        (True, 'Evet'),
        (False, 'Hayır'),
    )

    url = models.URLField(verbose_name="Portfolio Url", null=True, blank=True)
    categories = models.ManyToManyField(Category, verbose_name="Post Kategorisi", related_name='portfolio_categories')
    image = ProcessedImageField(**image_optimizer('uploads/portfolio', 640, 481, 85, 'avif'), null=True, 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)
    parent = models.ForeignKey('self', related_name='child', on_delete=models.CASCADE, blank=True, null=True,
                               editable=False,
                               verbose_name='Konular')

    class Meta:
        ordering = ["created_at"]
        db_table = 'portfolios'
        verbose_name_plural = "Portfolio"
        verbose_name = "Portfolio"

    def __str__(self):
        return f"Portfolio: {self.url if self.url else f'ID: {self.id}'}"
