"""
Models.py:
"""
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
from django.template.defaultfilters import slugify
from django.utils import timezone


# Create the main class to handle our BlogPosts
class BlogPost(models.Model):
    """
    post_author: The blog post author (creates foreign key).
    post_title: The blog post title.
    post_slug: Generates a slug for cleaner URLS (good for SEO).
    post_body: The main body/content of the blog post.
    created_date: The date the post was created.
    updated_date: States the date/time the post was last updated.
    published: States when the post was published.
    post_status: Returns the status, meaning is it in draft or published state.
    image_width: the image width
    image_height: the image height
    post_images: the images that will be displayed
    post_views: the number of views the post has recieved
    post_tags: the posts tags
    """

    # Create our settings that will be used in our blog posts.
    image_height = 500
    image_width = 300
    post_title = models.CharField(max_length=40)
    slug = models.SlugField(max_length=40, unique=True)
    post_body = models.TextField()
    post_author = models.ForeignKey(User, related_name='blog_posts')
    created_date = models.DateTimeField(default=timezone.now)
    published_date = models.DateTimeField(blank=True, null=True)
    post_images = models.ImageField(upload_to='users/blog_post_images/%d/%m/%Y',\
    height_field='image_height', width_field='image_width', blank=True)
    post_views = models.IntegerField(default=0)  # record the number of post views
    post_tags = models.CharField(max_length=30, blank=True, null=True)

    def __unicode__(self):
        return self.post_title

    # fetches the post based on a slug
    @models.permalink
    def get_absolute_url(self):
        """
        gets the absolute url of the blog post
        """
        return ('blog_post_detail', (), {'slug': self.slug})

    # auto generates a slug by overriding the model save method, sets self.slug to
    # the slug generated by the slugify helper function then calls the parent save method
    def save(self, *args, **kwargs):  # pylint: disable=W0221
        """
        override the save method with our custom slugfield
        """
        if not self.slug:
            self.slug = slugify(self.post_title)
        super(BlogPost, self).save(*args, **kwargs)

    # publish the blog post
    def publish(self):
        """
        publish our blog post, we set the published date
        then save the post
        """
        self.published_date = timezone.now()
        self.save()
