from datetime import datetime

from django.contrib.auth import get_user_model
from django.contrib.postgres.indexes import GinIndex
from django.contrib.postgres.search import SearchVector, SearchVectorField
from django.db import models
from model_utils.fields import AutoLastModifiedField
from model_utils.models import TimeStampedModel

User = get_user_model()


def user_directory_path(instance, filename):
    timestr = str(datetime.now().strftime('%Y_%m_%d_%H_%M_%S'))
    new_filename = filename.split(".")
    return (
        'blogs_abc/{0}_{1}.{2}'.format(
            instance.user.id, timestr, new_filename[len(new_filename) - 1]
        )
        if instance.user
        else 'blogs_abc/{0}_{1}.{2}'.format(
            instance.id, timestr, new_filename[len(new_filename) - 1]
        )
    )


class PostCategory(models.Model):
    date = models.DateTimeField(auto_now=True)
    name = models.CharField(max_length=250, unique=True)
    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return('home')

class PostTag(models.Model):
    date = models.DateTimeField(auto_now=True)
    name = models.CharField(max_length=250, unique=True)
    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return('home')

STATUS = (
    (0, "Draft"),
    (1, "Publish")
)


class Blog(TimeStampedModel):
    title = models.CharField(max_length=200, unique=True, db_index=True)
    first_letter = models.CharField(
        max_length=1,
        db_index=True,
        blank=True,
        null=True,
        help_text='First letter of name',
    )
    summary = models.TextField(blank=True, null=True)
    body = models.TextField(blank=True, null=True)
    status = models.IntegerField(choices=STATUS, default=0)
    date_create = models.DateTimeField(auto_now=True)
    date_modify = AutoLastModifiedField()
    category = models.ForeignKey(
        'PostCategory',
        null=True,
        related_name='category',
        on_delete=models.CASCADE,
    )
    tags = models.ManyToManyField(PostTag, blank=True)

    # Search
    search_vector = SearchVectorField(
        null=True,
        blank=True,
        editable=False,
    )  # https://docs.djangoproject.com/en/4.0/ref/contrib/postgres/search/#searchvectorfield

    class Meta:
        verbose_name_plural = 'Blog'
        indexes = [
            GinIndex(
                fields=[
                    'search_vector',
                ]
            ),
        ]
        ordering = ['-date_create']

    @staticmethod
    def get_search_vector():
        return SearchVector('name')

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return('home')
