from django.db import models
from django.contrib.auth.models import User
from django.utils.text import slugify
import uuid
from django.core.exceptions import ValidationError
from django.utils import timezone

class QuizImage(models.Model):
    image = models.ImageField(max_length=256,verbose_name="Bild", upload_to='quiz_images/', blank=True, null=True)  # Bild speichern in media/quiz_images/


class QuestionImage(models.Model):
     image = models.ImageField(verbose_name="Bild", upload_to="question_images/", blank=True, null=True)


class QivipQuiz(models.Model):
    STATUS_VALUES = {
        "öffentlich": "Öffentlich",
        #"versteckt": "Versteckt",
        "privat": "Privat",
    }
    DIFFICULTY_VALUES = {
        "1": "1",
        "2": "2",
        "3": "3",
        "4": "4",
        "5": "5",
        "nicht gesetzt":"nicht gesetzt",

    }



        
    def validate_description(value):
        if value.strip() == "In dem Quiz geht es um ...":
            raise ValidationError("Bitte gib eine aussagekräftige Beschreibung ein.")

    image = models.ForeignKey(
    QuizImage,
    null=True,
    blank=True,
    on_delete=models.PROTECT, 
    related_name="quizzes"
    )


    uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
    user_id = models.ForeignKey(User, on_delete=models.CASCADE, related_name='quiz')
    #creator = models.ForeignKey(User, on_delete=models.SET_NULL,blank=True, null=True, related_name='creator_quiz')
    base_quiz = models.ForeignKey('self', on_delete=models.SET_NULL,blank=True, null=True, related_name='child_quizzes')
    creation_date = models.DateTimeField(auto_now_add=True)
    update_date = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length=10, choices=list(STATUS_VALUES.items()), default="öffentlich")
    category = models.ForeignKey('QuizCategory',verbose_name="Kategorie", related_name='quiz', on_delete=models.CASCADE)
    name = models.CharField(max_length=75,verbose_name="Name des Quizzes")
    description = models.TextField(validators=[validate_description],max_length=200,blank=False, default="In dem Quiz geht es um ...", verbose_name="Beschreibung")
    difficulty= models.CharField(verbose_name="Schwierigkeit", max_length=13, choices=list(DIFFICULTY_VALUES.items()), default="nicht gesetzt", help_text="1: niedrigste Schwierigkeit und 5: höchste Schwierigkeit")
    credits=models.TextField(blank=True, editable=True)
    average_rating = models.FloatField(default=3.0)
    rating_count = models.IntegerField(default=0)
    published_at = models.DateTimeField(null=True, blank=True)  # manuell gesetzt, wenn veröffentlicht

    def is_published(self):
        return self.published_at is not None and self.published_at <= timezone.now()
    def __str__(self):

        return self.name

class QivipQuizFavorite(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)  # Verknüpfung zu User
    quiz = models.ForeignKey(QivipQuiz, on_delete=models.CASCADE, related_name='favorites')  # Verknüpfung zu Quiz
    favorite = models.BooleanField(default=False)  # Favoritenstatus
    favorite_date = models.DateTimeField(null=True, blank=True) 

    class Meta:
        unique_together = ('user', 'quiz')  # Sicherstellen, dass es nur ein Favorit pro User und Quiz gibt


# Create your models here.
class QivipQuestion(models.Model):
    
    TIME_VALUES = {
        "10": 10,
        "15": 15,
        "30": 30,
        "60": 60,
        "90": 90,
        "120": 120,
        "180": 180,
    }
    uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
    quiz_id = models.ForeignKey(QivipQuiz, on_delete=models.CASCADE, related_name='questions')
    creation_date = models.DateTimeField(auto_now_add=True)
    update_date = models.DateTimeField(auto_now=True)
    data = models.TextField()
    time_per_question = models.CharField(max_length=3, choices=list(TIME_VALUES.items()), default=30, help_text="Zeit pro Frage in Sekunden")
    image = models.ForeignKey(
    QuestionImage,
    null=True,
    blank=True,
    on_delete=models.PROTECT,
    related_name="questions"
)
    credits=models.TextField(blank=True, editable=True)

    def __str__(self):
        return self.data[:50]



class QuizRating(models.Model):
    quiz = models.ForeignKey(QivipQuiz, on_delete=models.CASCADE, related_name='ratings')
    participant_id = models.CharField(max_length=200)
    rating = models.IntegerField(choices=[(i, str(i)) for i in range(1, 6)])
    created_at = models.DateTimeField(auto_now_add=True)

    #class Meta:
        #unique_together = ('quiz', 'participant_id')

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)

        # Update quiz average rating (immer, auch bei Updates)
        quiz = self.quiz
        total_ratings = quiz.ratings.count()
        avg_rating = quiz.ratings.aggregate(models.Avg('rating'))['rating__avg']
        quiz.average_rating = round(avg_rating, 1) if avg_rating else 3.0
        quiz.rating_count = total_ratings
        quiz.save()


"""
    def save(self, *args, **kwargs):
        is_new = self.pk is None
        super().save(*args, **kwargs)

        if is_new:
            # Update quiz average rating
            quiz = self.quiz
            total_ratings = quiz.ratings.count()
            avg_rating = quiz.ratings.aggregate(models.Avg('rating'))['rating__avg']
            quiz.average_rating = round(avg_rating, 1) if avg_rating else 3.0
            quiz.rating_count = total_ratings
            quiz.save()"""

class QuizCategory(models.Model):
    name = models.CharField(max_length=100, unique=True)
    description = models.TextField(blank=True, null=True)
    slug = models.SlugField(unique=True, blank=True)
    color= models.CharField(
        max_length=7,
        default="#000000",
        help_text="Farbe als Hex-Code, z.B. #ff0000"
    )


    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.name)
        super().save(*args, **kwargs)

    def __str__(self):
        return self.name