from django.conf import settings
from django.db import models
from django.urls import reverse
from django.utils.text import slugify
from django.utils import timezone
from django.contrib.auth.models import User


class Book(models.Model):
    """ Represents a single BOOK Book. """
    title = models.CharField(max_length=settings.PROJECT_BOOK_TITLE_MAX_LENGTH, unique=True,
                             help_text="Title of your Book.")
    author = models.ForeignKey(User, on_delete=models.PROTECT,
                               help_text="The user that posted this article.")
    slug = models.CharField(max_length=settings.PROJECT_BOOK_TITLE_MAX_LENGTH, blank=True, editable=False,
                            help_text="Unique URL path to access this Book. Generated by the system.")
    content = models.TextField(
        help_text="Write the content of your Book here.")
    created = models.DateTimeField(auto_now_add=True,
                                   help_text="The date and time this Book was created. Automatically generated when the model saves.")
    modified = models.DateTimeField(auto_now=True,
                                    help_text="The date and time this Book was updated. Automatically generated when the model updates.")

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        """ Returns a fully-qualified path for a Book (/my-new-BOOKS-Book). """
        path_components = {'slug': self.slug}
        return reverse('book-details-project', kwargs=path_components)
        # return reverse('books:books-update-Book', kwargs=path_components)
    def save(self, *args, **kwargs):
        """ Creates a URL safe slug automatically when a new a Book is created. """
        if not self.pk:
            self.slug = slugify(self.title, allow_unicode=True)

        # Call save on the superclass.
        return super(Book, self).save(*args, **kwargs)
