from django.utils import timezone
from django.shortcuts import render
from django.shortcuts import render, redirect, get_object_or_404, reverse
from play.models import QuizGame, QuizGameParticipant
from library.models import QivipQuiz
from django.http import HttpResponseRedirect, HttpResponseNotFound
from django.contrib import messages
from django.conf import settings

import json
import qrcode
import base64
from io import BytesIO
from django.shortcuts import render

# Create your views here.
def lobby(request, join_code):
    relative_url = reverse("play:create_participant", kwargs={"join_code": join_code})
    full_url = request.build_absolute_uri(relative_url)

    qr = qrcode.make(full_url)
    buffer = BytesIO()
    qr.save(buffer, format="PNG")
    img_base64 = base64.b64encode(buffer.getvalue()).decode("utf-8")

    
    
    quiz_game = get_object_or_404(QuizGame, join_code=join_code)
    quiz = get_object_or_404(QivipQuiz, pk=quiz_game.quiz_id.id)
    context = {
        'quiz': quiz,
        'quiz_game': quiz_game,
        "qr_code_base64": img_base64,
    }


    mode = request.GET.get('mode','default')
    request.session['mode'] = mode
    if "host_id" in request.COOKIES:
        host_id = request.COOKIES['host_id']
        if host_id == quiz_game.host_id:
            context['host_id'] = host_id
            context["qr_code_base64"] = img_base64
            return render(request, 'play/lobby.html', context=context)
        elif mode=="learn":
            return redirect('play:create_participant', join_code=join_code)
        
    


    if not "participant_id" in request.COOKIES:
        return redirect('play:create_participant', join_code=join_code)

    participant_id = request.COOKIES['participant_id']
    try:
        participant = QuizGameParticipant.objects.get(participant_id=participant_id)
        if not participant.quiz_game.join_code == join_code: # Teilnehmer dem richtigen Spiel hinzufügen
            participant.quiz_game = quiz_game
            participant.score = 0  # Reset score when joining new game
            participant.last_score = 0
            participant.save()
    except QuizGameParticipant.DoesNotExist:
        return redirect('play:create_participant', join_code=join_code)

    context['participant'] = participant
    context["qr_code_base64"] = img_base64
    return render(request, 'play/lobby.html', context=context)

def select_mode(request,join_code):
    return render(request, 'play/select_mode.html', {'join_code': join_code})



def create_participant(request, join_code):
    mode = request.GET.get('mode','default')
    request.session['mode'] = mode
    quiz_game = get_object_or_404(QuizGame, join_code=join_code)
    if mode!="learn":
     if "participant_id" in request.COOKIES:
        # Prüfe ob der Teilnehmer noch existiert
        participant_id = request.COOKIES['participant_id']
        try:
            participant = QuizGameParticipant.objects.get(participant_id=participant_id)
            if participant.quiz_game.join_code != join_code:
                participant.quiz_game = quiz_game
                participant.score = 0  # Reset score when joining new game
                participant.last_score = 0
                participant.save()
            return redirect('play:lobby', join_code=join_code)
        except QuizGameParticipant.DoesNotExist:
            # Cookie löschen wenn Teilnehmer nicht mehr existiert
            response = HttpResponseRedirect(request.path)
            response.delete_cookie('participant_id')
            return response

     if request.method == 'POST':
        display_name = request.POST.get('display_name')
        if not display_name:
            return render(request, 'play/initialize_participant.html', {
                'join_code': join_code,
                'error': 'Bitte geben Sie einen Namen ein'
            })

        participant = QuizGameParticipant()
        participant.display_name = display_name
        participant.quiz_game = quiz_game
        participant.score = 0  # Initialize score
        participant.last_score = 0
        participant.save()

        response = HttpResponseRedirect(reverse('play:lobby', kwargs={'join_code': join_code}))
        response.set_cookie('participant_id', participant.participant_id, max_age=3600)
        return response

     return render(request, 'play/initialize_participant.html', {'join_code': join_code})
    else:
        messages.error(request, "Beitritt nicht möglich.")
        return render(request, 'play/join_game.html')
def create_game(request, quiz_id):
    
    try:
        quiz = QivipQuiz.objects.get(id=quiz_id)
        game = QuizGame()
        game.quiz_id = quiz
        game.host_id = game.generate_unique_id()
        game.save()


        response = HttpResponseRedirect(reverse('play:select_mode', kwargs={'join_code': game.join_code}))
        response.set_cookie('host_id', game.host_id, max_age=3600)
        
        return response
    except QivipQuiz.DoesNotExist:
        return HttpResponseNotFound("Quiz nicht gefunden")
    

def join_game(request):
    if request.method == 'POST':
        join_code = request.POST.get('game_code')
        try:
            quiz = QuizGame.objects.get(join_code=join_code)
            # Redirect to create_participant if no participant cookie exists
            if not "participant_id" in request.COOKIES:
                return redirect('play:create_participant', join_code=join_code)
            return redirect('play:lobby', join_code=join_code)
        except QuizGame.DoesNotExist:
            messages.error(request, "Dieses Spiel existiert nicht.")
    return render(request, 'play/join_game.html')



def scores(request, join_code):
    quiz_game = get_object_or_404(QuizGame, join_code=join_code)

    # Verify game state
    if quiz_game.current_state != 'scores':
        return redirect('play:lobby', join_code=join_code)
    
    # Get participants sorted by score
    participants = QuizGameParticipant.objects.filter(quiz_game=quiz_game).order_by('-score')
    
    # Check if user is host
    is_host = False
    if 'host_id' in request.COOKIES and request.COOKIES['host_id'] == quiz_game.host_id:
        is_host = True
    
    # Get current question for context
    questions = quiz_game.quiz_id.questions.all()
    current_question = questions[quiz_game.current_question_index]
    question_data = json.loads(current_question.data)
    
    try:
        my_participant = request.session.get('my_participant-participant_id')
        participant = QuizGameParticipant.objects.get(participant_id=my_participant)
        my_participant=participant
    except:
        participant = QuizGameParticipant.objects.none()

    return render(request, 'play/game/score_overview.html', {
        'quiz_game': quiz_game,
        'participants': participants,
        'participant': participant,
        'my_participant':my_participant,
        'is_host': is_host,
        'host_id': quiz_game.host_id if is_host else None,
        'is_last_question': quiz_game.current_question_index + 1 >= len(questions),
        'question_data': question_data,
        'question_index': quiz_game.current_question_index,
        'total_questions': len(questions)
    })


def scoreboard(request, join_code):
    quiz_game = get_object_or_404(QuizGame, join_code=join_code)

    # Verify game state
    if quiz_game.current_state != 'scoreboard':
        return redirect('play:lobby', join_code=join_code)
    
    # Get participants sorted by score
    participants = QuizGameParticipant.objects.filter(quiz_game=quiz_game).order_by('-score')
    
    # Check if user is host
    is_host = False
    if 'host_id' in request.COOKIES and request.COOKIES['host_id'] == quiz_game.host_id:
        is_host = True
    
    # Get current question for context
    questions = quiz_game.quiz_id.questions.all()
    current_question = questions[quiz_game.current_question_index]
    question_data = json.loads(current_question.data)
    
    try:
        my_participant = request.session.get('my_participant-participant_id')
        participant = QuizGameParticipant.objects.get(participant_id=my_participant)
        my_participant=participant
    except:
        participant = QuizGameParticipant.objects.none()

    return render(request, 'play/game/scoreboard.html', {
        'quiz_game': quiz_game,
        'participants': participants,
        'participant': participant,
        'my_participant':my_participant,
        'is_host': is_host,
        'host_id': quiz_game.host_id if is_host else None,
        'is_last_question': quiz_game.current_question_index + 1 >= len(questions),
        'question_data': question_data,
        'question_index': quiz_game.current_question_index,
        'total_questions': len(questions)
    })


"""
def finished(request, join_code):
    
    quiz_game = get_object_or_404(QuizGame, join_code=join_code)
    
    # Verify game state
    if quiz_game.current_state != 'finished':
        return redirect('play:lobby', join_code=join_code)
    
    # Get participants sorted by score
    participants = QuizGameParticipant.objects.filter(quiz_game=quiz_game).order_by('-score')
    
    # Check if user is host
    is_host = False
    if 'host_id' in request.COOKIES and request.COOKIES['host_id'] == quiz_game.host_id:
        is_host = True

    # Get participant if exists
    participant_id = request.COOKIES.get('participant_id')
    participant = None
    if participant_id:
        participant = QuizGameParticipant.objects.filter(
            quiz_game=quiz_game,
            participant_id=participant_id
        ).first()
    
    return render(request, 'play/game/finished.html', {
        'quiz_game': quiz_game,
        'participants': participants,
        'winner': participants.first() if participants.exists() else None,
        'join_code': join_code,
        'is_host': is_host,
        'participant_id': participant_id if participant else None
    })
"""


def winner_podest(request, join_code):
    quiz_game = get_object_or_404(QuizGame, join_code=join_code)

    # Verify game state
    if quiz_game.current_state != 'winner_podest':
        return redirect('play:lobby', join_code=join_code)
    
    # Get participants sorted by score
    participants = QuizGameParticipant.objects.filter(quiz_game=quiz_game).order_by('-score')
    
    # Check if user is host
    is_host = False
    if 'host_id' in request.COOKIES and request.COOKIES['host_id'] == quiz_game.host_id:
        is_host = True
    
    # Get current question for context
    questions = quiz_game.quiz_id.questions.all()
    current_question = questions[quiz_game.current_question_index]
    question_data = json.loads(current_question.data)
    
    try:
        my_participant = request.session.get('my_participant-participant_id')
        participant = QuizGameParticipant.objects.get(participant_id=my_participant)
        my_participant=participant
    except:
        participant = QuizGameParticipant.objects.none()

    return render(request, 'play/game/winner_podest.html', {
        'quiz_game': quiz_game,
        'participants': participants,
        'participant': participant,
        'my_participant':my_participant,
        'is_host': is_host,
        'host_id': quiz_game.host_id if is_host else None,
        'is_last_question': quiz_game.current_question_index + 1 >= len(questions),
        'question_data': question_data,
        'question_index': quiz_game.current_question_index,
        'total_questions': len(questions)
    })

def finished(request, join_code):
    quiz_game = get_object_or_404(QuizGame, join_code=join_code)
    
    if quiz_game.current_state != 'finished':
        return redirect('play:lobby', join_code=join_code)
    try:
        game = QuizGame.objects.get(join_code=join_code) 
        # Get participants sorted by score
        participants = QuizGameParticipant.objects.filter(quiz_game=quiz_game).order_by('-score')


        # Get participant if exists
        participant_id = request.COOKIES.get('participant_id')
        participant = None
        if participant_id:
            participant = QuizGameParticipant.objects.filter(
            quiz_game=quiz_game,
            participant_id=participant_id
        ).first()
            
        is_host = False
        if 'host_id' in request.COOKIES and request.COOKIES['host_id'] == quiz_game.host_id:
            is_host = True

        context = {
            'join_code': join_code,
            'is_host': is_host,
            'participants': participants,
            'participant_id': participant_id if participant else None,
            'rating_enabled': settings.QIVIP_CONFIG['ENABLE_RATING_SYSTEM']
        }
        return render(request, 'play/game/finished.html', context)
    except QuizGame.DoesNotExist:
        return redirect('home')
      

def question(request, join_code):
    quiz_game = get_object_or_404(QuizGame, join_code=join_code)
    
    # Verify game state
    if quiz_game.current_state != 'question':
        return redirect('play:lobby', join_code=join_code)
    
    # Get current question
    questions = quiz_game.quiz_id.questions.all()
    if quiz_game.current_question_index >= len(questions):
        return redirect('play:lobby', join_code=join_code)
    
    current_question = questions[quiz_game.current_question_index]
    question_data = json.loads(current_question.data)
    
    # Check if user is host
    if 'host_id' in request.COOKIES and request.COOKIES['host_id'] == quiz_game.host_id:
        return render(request, 'play/game/question_host.html', {
            'quiz_game': quiz_game,
            'question_data': question_data,
            'current_question':current_question,
            'host_id': quiz_game.host_id,
            'start_time': int(quiz_game.question_start_time.timestamp() * 1000),
            'question_index': quiz_game.current_question_index,
            'total_questions': len(questions),
            'question_image': current_question.image
        })
    
    # Handle participant view
    if not 'participant_id' in request.COOKIES:
        return redirect('play:create_participant', join_code=join_code)
    
    participant_id = request.COOKIES['participant_id']
    try:
        participant = QuizGameParticipant.objects.get(participant_id=participant_id)
        
   
    except QuizGameParticipant.DoesNotExist:
        return redirect('play:create_participant', join_code=join_code)
    request.session['my_participant-participant_id'] = participant.participant_id
    
    return render(request, 'play/game/question_participant.html', {
        'quiz_game': quiz_game,
        'question_data': question_data,
        'current_question':current_question,
        'participant': participant,
        'start_time': int(quiz_game.question_start_time.timestamp() * 1000),
        'question_index': quiz_game.current_question_index,
        'total_questions': len(questions),
    })

def waiting_room(request, join_code):
    quiz_game = get_object_or_404(QuizGame, join_code=join_code)
    
    # Check if user is host
    if 'host_id' in request.COOKIES and request.COOKIES['host_id'] == quiz_game.host_id:
        return redirect('play:question', join_code=join_code)
    
    # Handle participant view
    if not 'participant_id' in request.COOKIES:
        return redirect('play:create_participant', join_code=join_code)
    
    participant_id = request.COOKIES['participant_id']
    try:
        participant = QuizGameParticipant.objects.get(participant_id=participant_id)
    except QuizGameParticipant.DoesNotExist:
        return redirect('play:create_participant', join_code=join_code)
    
    return render(request, 'play/game/wait_for_other_players.html', {
        'quiz_game': quiz_game,
        'participant': participant
    })


def selected_mode(request, join_code):
     


    mode = request.GET.get('mode','default')
    request.session['mode'] = mode
    quiz_game = get_object_or_404(QuizGame, join_code=join_code)
    quiz = get_object_or_404(QivipQuiz, pk=quiz_game.quiz_id.id)
    QuizGameParticipant.objects.filter(quiz_game=quiz_game).delete()   

# Hier werden die Fragen gemischt!
    import random
    questions = quiz_game.quiz_id.questions.all()
    for question in questions:
        try:
            data = json.loads(question.data)
            if (data.get('type') == 'order' or  data.get('type') == 'multiple_choice') and 'options' in data:
                
                random.shuffle(data['options'])
                question.data = json.dumps(data)
                question.save(update_fields=['data'])
        except Exception:
            pass
    
    context = {
        'quiz': quiz,
        'quiz_game': quiz_game,
    }
    if "host_id" in request.COOKIES:
        host_id = request.COOKIES['host_id']
        if host_id == quiz_game.host_id:
            context['host_id'] = host_id

        if mode=="learn":
            participant = QuizGameParticipant()
            if request.user.is_authenticated:
                participant.display_name = request.user.username
            else:
                participant.display_name = "SIE"
  
            participant.participant_id=host_id
            participant.quiz_game = quiz_game
            participant.score = 0  # Initialize score
            participant.last_score = 0
            participant.save()
            quiz_game.current_state = "question"
            quiz_game.question_start_time = timezone.now()
            quiz_game.save()
  
            return redirect('play:question',join_code)
        
        return redirect('play:lobby', join_code=join_code)
        
