from django.db import models
from django.utils.text import slugify
from django.urls import reverse
from django.core.validators import FileExtensionValidator
from PIL import Image

class BlogCategories(models.Model):
    title = models.CharField(max_length=100, blank=True)
    slug = models.SlugField(unique=True, blank=True, null=True)
    picture = models.ImageField(upload_to='blog/images', null=True, blank=True)
    citation = models.TextField(blank=True)
    parentcategory = models.ManyToManyField('self', symmetrical=False, blank=True)
    
    class Meta:
        verbose_name_plural = 'Blog Categories'

    IMAGE_MAX_SIZE = (500,350)
    def resize_image(self):
        if self.picture:
            picture = Image.open(self.picture)
            picture.thumbnail(self.IMAGE_MAX_SIZE)
            picture.save(self.picture.path)
    
    def save(self, *args, **kwargs):
        if not self.slug:
            base_slug = slugify(self.title)
            slug = base_slug
            counter = 1
            while Articles.objects.filter(slug=slug).exists():
                slug = '{}-{}'.format(base_slug, counter)
                counter += 1
            self.slug = slug
        self.resize_image()
        super().save(*args, **kwargs)
        

    def __str__(self):
        return self.title

class Articles(models.Model):
    title = models.CharField(max_length=200)
    author = models.ForeignKey('authentication.User', on_delete=models.CASCADE)
    slug = models.SlugField(unique=True, blank=True, null=True)
    category = models.ManyToManyField('BlogCategories')
    image = models.ImageField(upload_to='blog/images')
    content = models.TextField(blank=True)
    date_created = models.DateTimeField(auto_now_add=True)
    date_updated = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name_plural = 'Articles'

    IMAGE_MAX_SIZE = (600, 400)

    def resize_image(self):
        image = Image.open(self.image)
        image.thumbnail(self.IMAGE_MAX_SIZE)
        image.save(self.image.path)

    def save(self, *args, **kwargs):
        if not self.slug:
            base_slug = slugify(self.title)
            slug = base_slug
            counter = 1
            while Articles.objects.filter(slug=slug).exists():
                slug = '{}-{}'.format(base_slug, counter)
                counter += 1
            self.slug = slug
        self.resize_image()
        super().save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse('blog:article_detail', kwargs={'slug': self.slug})

    def __str__(self):
        return self.title

class Images(models.Model):
    title = models.CharField(max_length=33, blank=True)
    article = models.ForeignKey('Articles', related_name="articles", on_delete=models.CASCADE)
    file = models.ImageField(upload_to='dashboard/images', blank=True, null=True)
    
    class Meta:
        verbose_name_plural = 'Images'
    
    IMAGE_MAX_SIZE = (500, 350)
    
    def resize_image(self):
        file = Image.open(self.file)
        file.thumbnail(self.IMAGE_MAX_SIZE)
        file.save(self.file.path)
    
    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        self.resize_image()

    def __str__(self):
        return self.title

class Comment(models.Model):
    commentaire = models.TextField(blank=True)
    article = models.ForeignKey(Articles, null=True, on_delete=models.CASCADE)
    user = models.ForeignKey('authentication.User', on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add=True)
    active = models.BooleanField(default=False)
    class Meta:
        verbose_name_plural = 'Comments'
    def __str__(self):
        return self.commentaire

