from django.db import models
from django.utils import timezone
from django.contrib.contenttypes.fields import GenericRelation

from .Question import Question
from .LikeDislike import LikeDislike
from .Profile import User


class Answer(models.Model):
    answer_id = models.AutoField(primary_key=True)
    text = models.TextField()
    updated_at = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    is_correct = models.BooleanField(default=False)
    rating = models.IntegerField(default=0)

    votes = GenericRelation(LikeDislike, related_query_name='answers')

    def __str__(self):
        return self.text

    def count_rating(self):
        return self.votes.likes().count() - self.votes.dislikes().count()

    def author_name(self):
        return self.author.username