from django.db import models
from django.contrib.auth.models import User
from library.models import QivipQuiz
from django.http import response
import random, string

# Create your models here.
class QuizGame(models.Model):
    GAME_STATES = [
        ('lobby', 'In Lobby'),
        ('question', 'Frage läuft'),
        ('scores', 'Punkteübersicht'),
        ('winner_podest','Siegerpodest'),
        ('finished', 'Beendet'),
        ('scoreboard', 'Scoreboard'),
        
    ]
    
    host_id = models.CharField(max_length=200, unique=True)
    join_code = models.CharField(max_length=6, unique=True, blank=True)
    quiz_id = models.ForeignKey(QivipQuiz, on_delete=models.CASCADE)
    current_state = models.CharField(max_length=20, choices=GAME_STATES, default='lobby')
    current_question_index = models.IntegerField(default=0)
    question_start_time = models.DateTimeField(null=True, blank=True)
    updated_at = models.DateTimeField(auto_now=True)

    def save(self, *args, **kwargs):
        if not self.join_code:
            self.join_code = self.generate_unique_code()        
        super().save(*args, **kwargs)

    def generate_unique_code(self):
        for i in range(10):
            new_code = ''.join(random.choices(string.digits, k=6))
            if not QuizGame.objects.filter(join_code=new_code).exists():
                return new_code

    def generate_unique_id(self):
        for i in range(10):
            new_id = ''.join(random.choices(string.digits + string.ascii_lowercase, k=60))
            if not QuizGameParticipant.objects.filter(participant_id=new_id).exists():
                return new_id

class QuizGameParticipant(models.Model):
    participant_id = models.CharField(max_length=200, unique=True)
    display_name = models.CharField(verbose_name="Anzeigename", max_length=15)
    quiz_game = models.ForeignKey(QuizGame, on_delete=models.CASCADE, related_name="participants")
    score = models.IntegerField(verbose_name="Punkte", default=0)
    last_score = models.IntegerField(verbose_name="Letzte_Punkte", default=0)
    avatar = models.CharField(max_length=200, blank=True, default="")
    last_heartbeat = models.DateTimeField(auto_now_add=True)
    last_answer = models.IntegerField(null=True, blank=True)
    coordinate_answer = models.CharField(null=True, blank=True,max_length=256)
    last_answer_correct = models.BooleanField(null=True, blank=True)

    def save(self, *args, **kwargs):
        if not self.participant_id:
            self.participant_id = self.generate_unique_id()
        super().save(*args, **kwargs)
        
    def generate_unique_id(self):
        for i in range(10):
            new_id = ''.join(random.choices(string.digits + string.ascii_lowercase, k=60))
            if not QuizGameParticipant.objects.filter(participant_id=new_id).exists():
                return new_id

class QuizAnswer(models.Model):
    participant = models.ForeignKey(QuizGameParticipant, on_delete=models.CASCADE, related_name='answers')
    question_index = models.IntegerField()
    answer_index = models.IntegerField(null=True, blank=True)  # für MC, TF
    answer_text = models.TextField(null=True, blank=True)      # für Input
    answers_order = models.JSONField(null=True, blank=True)     # NEU für "order"
    is_correct = models.BooleanField()
    score = models.IntegerField()
    time_remaining = models.IntegerField()
    
    class Meta:
        unique_together = ['participant', 'question_index']

    def generate_unique_id(self):
        for i in range(10):
            new_id = ''.join(random.choices(string.digits + string.ascii_lowercase, k=60))
            if not QuizGameParticipant.objects.filter(participant_id=new_id).exists():
                return new_id