import json
from django.shortcuts import render, get_object_or_404, redirect
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from .models import Level, Question, Option, Score

def index(request):
    levels = Level.objects.all()
    context = {
        'levels': levels,
        'title': 'Իմ հայրենիք - Գլխավոր',
    }
    return render(request, 'core/index.html', context)

def quiz_view(request, level_id):
    level = get_object_or_404(Level, id=level_id)
    questions = level.questions.all()
    
    # Shuffle or select specific questions if needed
    question_data = []
    for q in questions:
        options = []
        for opt in q.options.all():
            options.append({
                'id': opt.id,
                'text': opt.text,
                'is_correct': opt.is_correct
            })
        question_data.append({
            'id': q.id,
            'text': q.text,
            'points': q.points,
            'time_limit': q.time_limit,
            'options': options
        })
    
    context = {
        'level': level,
        'questions_json': json.dumps(question_data),
        'title': f'Իմ հայրենիք - {level.title}',
    }
    return render(request, 'core/quiz.html', context)

@csrf_exempt
def submit_score(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            player_name = data.get('player_name', 'Անանուն')
            score_value = data.get('score', 0)
            level_id = data.get('level_id')
            
            level = Level.objects.get(id=level_id)
            score_obj = Score.objects.create(
                player_name=player_name,
                score=score_value,
                level=level
            )
            return JsonResponse({'status': 'success', 'score_id': score_obj.id})
        except Exception as e:
            return JsonResponse({'status': 'error', 'message': str(e)}, status=400)
    return JsonResponse({'status': 'error', 'message': 'Invalid request method'}, status=405)

def leaderboard(request):
    top_scores = Score.objects.all()[:10]
    context = {
        'top_scores': top_scores,
        'title': 'Իմ հայրենիք - Լավագույնները',
    }
    return render(request, 'core/leaderboard.html', context)