from django.db import models
from django.contrib.auth.models import User
from django.template.defaultfilters import slugify
from django.shortcuts import reverse
from django.conf import settings
from ckeditor.fields import RichTextField
from ckeditor_uploader.fields import RichTextUploadingField

class Category(models.Model):
    name = models.CharField(max_length=255)
    description = models.TextField()
    slug = models.SlugField(max_length=255)
    ordering = models.IntegerField(default=0)

    class Meta:
        verbose_name_plural = 'Kategori'
        ordering = ('ordering',)
    
    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        if self.slug == None:
            slug = slugify(self.name)

            has_slug = Category.objects.filter(slug=slug).exists()
            count = 1
            while has_slug:
                count += 1
                slug = slugify(self.title) + '-' + str(count)
                has_slug = Category.objects.filter(slug=slug).exists()
            self.slug =slug

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

# ___________________________________

class Link(models.Model):
    category = models.ForeignKey("category",on_delete=models.SET_NULL,null=True,blank=True)
    title = models.CharField(max_length=100)
    caption = models.CharField(max_length=50, blank=True, null=True)
    icon = models.CharField(max_length=100, blank=True, null=True)
    button_class = models.CharField(max_length=100, blank=True, null=True)
    button_style = models.CharField(max_length=100, blank=True, null=True)
    link_url = models.CharField(('Link'),max_length=200, blank=True, null=True)
    thumbnail = models.ImageField(upload_to=settings.MEDIA, null=True, blank=True)
    isi = RichTextUploadingField(blank=True, null=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    date_added = models.DateTimeField(auto_now_add=True)

    STATUS = (
        ('Publish', 'Publish'),
        ('Draft', 'Draft'),
        ('InActive', 'InActive')
    )
    status = models.CharField(max_length=20, default='Publish', blank=True, choices=STATUS)

    featured = models.BooleanField(default=False)
    user_login = models.BooleanField(default=False)
    slug = models.SlugField(max_length=255, blank=True, null=True)

    class Meta:
        verbose_name_plural = 'Link'
        ordering = ('-date_added',)

    def __str__(self):
        return self.title
    
    def save(self, *args, **kwargs):
        if self.slug == None:
            slug = slugify(self.title)

            has_slug = Link.objects.filter(slug=slug).exists()
            count = 1
            while has_slug:
                count += 1
                slug = slugify(self.title) + '-' + str(count)
                has_slug = Link.objects.filter(slug=slug).exists()
            self.slug =slug
        
        super().save(*args, **kwargs)
        