from django.contrib import admin
from django.db import models
from django.utils import timezone

from _helpers.utils import jalali_converter, generate_unique_slug


class ObjectsQuerySet(models.QuerySet):
    def deleted_objects(self):
        return self.filter(is_deleted=True)

    def available_objects(self):
        return self.filter(is_deleted=False)

    def active_objects(self):
        return self.filter(is_active=True)

    def inactive_objects(self):
        return self.filter(is_active=False)


class BaseModel(models.Model):
    created = models.DateTimeField(auto_now_add=True, verbose_name="تاریخ ایجاد")
    updated = models.DateTimeField(auto_now=True, verbose_name="تاریخ بروزرسانی")
    is_active = models.BooleanField(default=True, verbose_name="فعال")
    is_deleted = models.BooleanField(default=False, verbose_name="حذف شده")
    deleted_at = models.DateTimeField(null=True, blank=True, verbose_name="تاریخ حذف")

    objects = ObjectsQuerySet.as_manager()

    class Meta:
        abstract = True

    def save(self, *args, **kwargs):
        if self.is_deleted:
            self.is_active = False
        super(BaseModel, self).save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        self.is_deleted = True
        self.deleted_at = timezone.now()
        self.save()

    def hard_delete(self):
        super().delete()

    def jcreated(self):
        return jalali_converter(self.created)

    jcreated.short_description = "تاریخ ایجاد"

    def jcreated_date(self):
        return self.jcreated().split(',')[0]

    jcreated_date.short_description = "تاریخ ایجاد"

    def jupdated(self):
        return jalali_converter(self.updated)

    jupdated.short_description = "تاریخ بروزرسانی"

    def jupdated_date(self):
        return self.jupdated().split(',')[0]

    jupdated_date.short_description = "تاریخ بروزرسانی"


class SluggedModel(BaseModel):
    slug = models.SlugField(max_length=100, unique=True, verbose_name="اسلاگ")

    class Meta:
        abstract = True

    def save(self, *args, **kwargs):
        if not self.slug:
            if hasattr(self, 'name'):
                self.slug = generate_unique_slug(self.name)
            else:
                self.slug = generate_unique_slug(str(self.created))
        super(BaseModel, self).save(*args, **kwargs)


class SelfParentModel(BaseModel):
    parent = models.ForeignKey('self', related_name='children',
                               on_delete=models.SET_NULL, null=True, blank=True, default=None,
                               verbose_name='زیرشاخه')

    class Meta:
        abstract = True


class NameSlugModel(SluggedModel):
    name = models.CharField(max_length=100, verbose_name="نام")

    class Meta:
        abstract = True

    def __str__(self):
        return self.name


class NameSlugAdminModel(admin.ModelAdmin):
    prepopulated_fields = {'slug': ('name',)}

    class Meta:
        abstract = True


class SelfParentNameSlugModel(SelfParentModel, NameSlugModel):
    class Meta:
        abstract = True


class TagModel(SelfParentModel, NameSlugModel):
    class Meta:
        abstract = True
        ordering = ['parent__id', 'name']

    def __str__(self):
        return self.name


class TagAdminModel(admin.ModelAdmin):
    fields = ['name', 'slug', 'parent', 'is_active']
    list_display = ['name', 'slug', 'parent', 'is_active', 'is_deleted', 'jcreated']
    list_filter = ['is_active', 'slug', 'parent', 'is_deleted']
    search_fields = ['name', 'slug', 'parent__name']
    prepopulated_fields = {'slug': ('name',)}
