from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
from enum import Enum

# Create your models here.
class PostState(Enum):
    DRAFT = 0
    PUBLISHED = 1
    WAITING_LIST = 2
    USER_SUBMITTED = 3

class Post(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    body = models.CharField(max_length=10000)
    url = models.CharField(max_length=200)
    date = models.DateTimeField('date published')
    state = models.IntegerField(default=0)
    style = models.IntegerField(default=0)
    image_url = models.CharField(max_length=100)
    def __str__(self):
        return self.title

    def top_comments(self):
        return self.comment_set.order_by('-voters').all()[:1]

    def flat_comments(self, user):
        flat = []
        for comment in self.comment_set.all():
            # flat.append(comment)
            flat.extend(comment.flat_children(0, user))
        return flat
        # return self.comment_set.annotate(ratings_num=count('voters')).order_by('-ratings_num')[:5]
        # return self.comment_set.order_by('voters_num').all()[:5]


class Comment(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    parent_comment = models.ForeignKey("self", on_delete=models.SET_NULL, null=True, blank=True)
    body = models.CharField(max_length=100)
    voters = models.ManyToManyField(User, related_name='voted_comments', null=True, blank=True)
    date = models.DateTimeField('date published')
    deleted = models.BooleanField(default=False)
    def __str__(self):
        return self.body

    def voters_count(self):
        return voters.count

    def upvoted_by(User):
        return user in self.voters

    def flat_children(self, level, user):
        self.level = range(level)
        self.upvoted = user in self.voters.all()
        self.score = len(self.voters.all())
        self.is_deletable = (self.deleted == False and user == self.author)
        flat = [self]
        for comment in self.comment_set.all():
            flat.extend(comment.flat_children(level + 1, user))
        return flat

class Player(models.Model):
    name = models.CharField(max_length=100)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    image_url = models.CharField(max_length=100)

    def __str__(self):
        return self.name
    # photo

class Tag(models.Model):
    name = models.CharField(max_length=100)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    def __str__(self):
        return self.name
