import os
from django.conf import settings
from django.core.files.base import ContentFile
from django.db import models
from imagekit.models import ProcessedImageField
from autoslug import AutoSlugField
from tinymce.models import HTMLField

from core.utils import image_optimizer
from reviews.models import RateableMixin  # RateableMixin import edildi


# 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')
    images = ProcessedImageField(**image_optimizer('uploads/category', 400, 400, 90, 'avif'), null=True, blank=True)

    class Meta:
        ordering = ["order"]
        db_table = 'categories'
        verbose_name_plural = "Ürün Kategorilerileri"
        verbose_name = "Ürün 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 Tags(models.Model):
    aktif = (
        (True, 'Evet'),
        (False, 'Hayır'),
    )
    tag = models.CharField(max_length=254, verbose_name="Ürün Tagları")
    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)
    slug = AutoSlugField(populate_from='tag', null=False, unique=True, editable=False, db_index=True)

    class Meta:
        ordering = ["-created_at"]
        db_table = 'tags'
        verbose_name_plural = "Ürün Tagları"
        verbose_name = "Ürün Tagı"
        unique_together = ('slug',)

    def get_slug(self):
        slug = self.tag.replace('ı', "i").replace('İ', 'i')
        number = 1
        while Tags.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 self.tag


class Images(models.Model):
    aktif = (
        (True, 'Evet'),
        (False, 'Hayır'),
    )
    title = models.CharField(max_length=254, verbose_name="Resim Başlığı")
    is_active = models.BooleanField(default=True, verbose_name='Yayındamı ?', choices=aktif)
    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")
    images = ProcessedImageField(**image_optimizer('uploads/images', 1500, 1500, 90, 'avif'), null=True, blank=True)


    class Meta:
        ordering = ["-created_at"]
        db_table = 'images'
        verbose_name_plural = "Galeri Resimleri"
        verbose_name = "Galeri Resmi"

    def __str__(self):
        return self.title



class Product(RateableMixin, models.Model):  # RateableMixin eklendi
    aktif = (
        (True, 'Evet'),
        (False, 'Hayır'),
    )
    birim = (
        ('Kg', 'Kg'),
        ('Adet', 'Adet'),
    )
    title = models.CharField(max_length=254, verbose_name="Ürün Başlığı")
    content = HTMLField(blank=True, null=True, verbose_name='Ürün İçeriği')
    categories = models.ManyToManyField(Category, verbose_name="Ürün Kategorisi", related_name='products')
    keywords = models.CharField(max_length=254, verbose_name="Seo Kelimeleri Aralarına Virgül Koyunuz")
    brim = models.CharField(max_length=10, verbose_name="Birim",choices=birim)
    price = models.FloatField(verbose_name='Birim Fiyatı',default='50')
    tags = models.ManyToManyField(Tags, verbose_name="Ürün Tagları", related_name='tags')
    gallery = models.ManyToManyField(Images, verbose_name="Galeri", related_name='gallery')
    images = ProcessedImageField(**image_optimizer('uploads/products', 260, 260, 90, 'avif'), null=True, blank=True)
    thumb = ProcessedImageField(**image_optimizer('uploads/products/thumb', 150, 150, 85, 'avif'), null=True, blank=True, editable=False)
    video = models.CharField(verbose_name="Video", null=True, blank=True, max_length=254, default='none')
    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 = 'products'
        verbose_name_plural = "Ürünler"
        verbose_name = "Ürün"
        unique_together = ('slug',)

    def get_slug(self):
        slug = self.title.replace('ı', "i").replace('İ', 'i')
        number = 1
        while Product.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()

        if self.images:
            # Eğer yeni bir kayıt ise veya resim değişmişse veya thumb yoksa
            update_thumb = False
            if not self.pk:
                update_thumb = True
            elif not self.thumb:
                # Thumb yoksa oluştur
                update_thumb = True
            else:
                try:
                    old_instance = self.__class__.objects.get(pk=self.pk)
                    if self.images != old_instance.images:
                        update_thumb = True
                except self.__class__.DoesNotExist:
                    pass

            if update_thumb:
                try:
                    if hasattr(self.images, 'closed') and self.images.closed:
                        self.images.open()

                    if hasattr(self.images, 'seek'):
                        self.images.seek(0)

                    content = self.images.read()
                    filename = os.path.basename(self.images.name)

                    # Doğrudan alana ata, super().save() işleyecek
                    self.thumb = ContentFile(content, name=filename)
                except Exception:
                    pass
                finally:
                    if hasattr(self.images, 'seek'):
                        self.images.seek(0)

        super().save(*args, **kwargs)

    def __str__(self):
        return f"Ürünler:  {self.title}"

class ProductTree(models.Model):
    aktif = (
        (True, 'Evet'),
        (False, 'Hayır'),
    )
    birim = (
        ('Kg', 'Kg'),
        ('Adet', 'Adet'),
    )
    title = models.CharField(max_length=254, verbose_name="Text")
    button = models.CharField(max_length=254, verbose_name="Button Text")
    content = models.TextField(blank=True, null=True, verbose_name='Ürün İçeriği')
    categories = models.ManyToManyField(Category, verbose_name="Ürün Kategorisi", related_name='product_trees')
    price = models.FloatField(verbose_name='Birim Fiyatı',default='50')
    images = ProcessedImageField(**image_optimizer('uploads/products', 740, 1100, 90, '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)
    is_front = models.BooleanField(default=True, verbose_name='Önde Görünsünmü ?', choices=aktif)

    class Meta:
        ordering = ["-created_at"]
        db_table = 'products_tree'
        verbose_name_plural = "Ürünler Tree"
        verbose_name = "Ürün Tree"

    def __str__(self):
        return f"Ürünler Tree:  {self.title}"

class Comment(models.Model):
    aktif = (
        (True, 'Evet'),
        (False, 'Hayır'),
    )
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='cuser')
    product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='_product')
    title = models.CharField(max_length=254, verbose_name="Yorum Başlığı")
    body = models.TextField(verbose_name='Yorum')
    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)
    slug = AutoSlugField(populate_from='title', null=False, unique=True, editable=False, db_index=True)
    parent = models.ForeignKey('self', related_name='child', on_delete=models.CASCADE, blank=True, null=True)

    class Meta:
        ordering = ["-created_at"]
        db_table = 'comments'
        verbose_name_plural = "Ürün Yorumları"
        verbose_name = "Ürüm Yorum"
        unique_together = ('slug', 'parent',)

    def get_slug(self):
        slug = self.title.replace('ı', "i").replace('İ', 'i')
        number = 1
        while Comment.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])
