from django.db import models
from django.contrib.auth import get_user_model
from django.urls import reverse
from tinymce import HTMLField
from cloudinary.models import CloudinaryField


User = get_user_model()

class PostView(models.Model):
	user=models.ForeignKey(User, on_delete=models.CASCADE)
	post=models.ForeignKey('Posting', on_delete=models.CASCADE)

	def __str__(self):
		return self.user.username

class Author(models.Model):
	user = models.OneToOneField(User, on_delete=models.CASCADE)
	profile_pic=CloudinaryField('image')

	def __str__(self):
		return self.user.username

class Category(models.Model):
	title=models.CharField(max_length=20)

	def __str__(self):
		return self.title


class Posting(models.Model):
	title=models.CharField(max_length=100)
	overview=models.TextField(blank=True, null=True)
	timestamp=models.DateTimeField(auto_now_add=True)
	comment_count=models.IntegerField(default=0)
	#view_count=models.IntegerField(default=0)
	author=models.ForeignKey(Author, on_delete=models.CASCADE)
	thumbnail=CloudinaryField('image')
	content = HTMLField()
	categories=models.ManyToManyField(Category)
	featured=models.BooleanField()
	previous_post= models.ForeignKey('self', related_name='previous', on_delete=models.SET_NULL, blank=True, null=True)
	next_post= models.ForeignKey('self', related_name='next', on_delete=models.SET_NULL, blank=True, null=True)

	def __str__(self):
		return self.title

	def get_absolute_url(self):
		return reverse('post_detail', kwargs={
			'id': self.id
			})
	def get_update_url(self):
		return reverse('post_update', kwargs={
			'id': self.id
			})
	def get_delete_url(self):
		return reverse('post_delete', kwargs={
			'id': self.id
			})

	@property
	def get_comments(self):
		return self.comments.all().order_by('-timestamp')
	
	@property
	def view_count(self):
		return PostView.objects.filter(post=self).count()
	

class Comment(models.Model):
	user=models.ForeignKey(User, on_delete=models.CASCADE)
	timestamp=models.DateTimeField(auto_now_add=True)
	content=models.TextField()
	post=models.ForeignKey(Posting, related_name='comments', on_delete=models.CASCADE)

	def __str__(self):
		return self.user.username






