from django.db import models
from django.utils.text import slugify
# Create your models here.



def get_unique_slug(value,model,slug_field='slug',max_length=None):
    if max_length is None and hasattr(model._meta.get_field(slug_field),'max_length'):
        max_length = model._meta.get_field(slug_field).max_length
    slug = slugify(value)
    num = 1
    if max_length:
        unique_slug = '{}-{}'.format(slug[:max_length - len(str(num)) - 1], num)
        while model.objects.filter(** {slug_field: unique_slug}).exists():
            unique_slug = '{}-{}'.format(slug[:max_length - len(str(num)) - 1], num)
            num += 1
    else:
        unique_slug = '{}-{}'.format(slug, num)
        while model.objects.filter(** {slug_field: unique_slug}).exists():
            unique_slug = '{}-{}'.format(slug, num)
            num += 1
    return unique_slug


def fill_unique_slug(instance,value_field,slug_field='slug',max_length=None):
    value = getattr(instance,value_field)
    slug = get_unique_slug(value,instance.__class__,slug_field=slug_field,max_length=max_length)
    setattr(instance,slug_field,slug)


class Post(models.Model):
    name = models.CharField(max_length=255)
    description = models.TextField()

    # len =1
    slug = models.SlugField(max_length=1, unique=True, blank=True, editable=False)
    # len =2
    slug2 = models.SlugField(max_length=3,blank=True, editable=False)
    # no len
    slug3 = models.SlugField(blank=True, editable=False)
    # len =4
    slug4 = models.SlugField(blank=True, editable=False)


    def __str__(self):
        return '%s | %s | %s | %s' %(self.slug,self.slug2,self.slug3,self.slug4)

    def save(self, *args, **kwargs):
        fill_unique_slug(self,'name')
        fill_unique_slug(self,'name','slug2',max_length=2)
        fill_unique_slug(self,'name','slug3')
        fill_unique_slug(self,'name','slug4',max_length=4)

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