from flask import Flask, render_template, request, redirect, url_for, session, Blueprint
import os
import random

# List of text files with questions
TEXTFILES = ["./templates/uni/subjects/portalfejlesztes_net_ben/kerdessor1_manual.txt", "./templates/uni/subjects/portalfejlesztes_net_ben/kerdessor2_manual.txt", "./templates/uni/subjects/portalfejlesztes_net_ben/kerdessor3.txt"]

# Define Blueprint for the portalfejlesztes quiz
portalfejlesztes_net_ben = Blueprint(
    'portalfejlesztes_net_ben', 
    __name__,
    template_folder='./templates'
)


# Parse the questions from text files
def parse_questions():
    content = []
    for file_path in TEXTFILES:
        with open(file_path, 'r', encoding='utf-8') as file:
            content.extend(file.read().split("\n\n"))

    questions = []

    for block in content:
        lines = block.strip().split("\n")
        question = lines[0].replace("Kérdés: ", "").strip()
        answers = []
        correct_answers = []

        for line in lines[1:]:
            answer = line.strip()
            if answer.startswith('!'):
                correct_answers.append(answer[1:].strip())
            else:
                answers.append(answer)

        if correct_answers:
            questions.append({
                'question': question,
                'answers': answers + correct_answers,
                'correct_answers': correct_answers
            })

    return questions

# Quiz route
@portalfejlesztes_net_ben.route('/')
@portalfejlesztes_net_ben.route('/quiz', methods=['GET', 'POST'])
def quiz():
    # If questions are not in session, parse and store them
    if 'quiz_questions' not in session:
        questions = parse_questions()
        quiz_questions = random.sample(questions, 20)
        session['quiz_questions'] = quiz_questions
        session['question_index'] = 0
        session['answers'] = []
    else:
        quiz_questions = session['quiz_questions']

    question_index = session.get('question_index', 0)

    # If all questions have been answered, redirect to results
    if question_index >= len(quiz_questions):
        return redirect(url_for('portalfejlesztes_net_ben.result'))

    current_question = quiz_questions[question_index]
    random.shuffle(current_question['answers'])  # Shuffle the answers

    return render_template('quiz.html', question=current_question, question_index=question_index)

# Submit answer route
@portalfejlesztes_net_ben.route('/submit_answer', methods=['POST'])
def submit_answer():
    user_answers = request.form.getlist('answer')  # Get multiple answers if needed
    question_index = int(request.form.get('question_index'))
    
    # Append answers to the session
    answers = session.get('answers', [])
    answers.append(user_answers)
    session['answers'] = answers

    # Update the question index
    question_index += 1
    session['question_index'] = question_index
    
    return redirect(url_for('portalfejlesztes_net_ben.quiz'))

# Result route
@portalfejlesztes_net_ben.route('/result')
def result():
    quiz_questions = session.get('quiz_questions', None)
    answers = session.get('answers', None)

    score = 0
    mistakes = []

    # Compare answers
    for i, user_answer in enumerate(answers):
        correct_answers = quiz_questions[i]['correct_answers']
        
        # If the user's answer matches the correct answer
        if set(user_answer) == set(correct_answers):
            score += 1
        else:
            mistakes.append({
                'question': quiz_questions[i]['question'],
                'correct_answer': correct_answers,
                'user_answer': user_answer
            })

    questions_with_answers = zip(quiz_questions, answers)

    return render_template('result.html', score=score, total=len(quiz_questions), mistakes=mistakes, questions_with_answers=questions_with_answers)

# Restart route
@portalfejlesztes_net_ben.route('/restart')
def restart():
    session.pop('question_index', None)
    session.pop('answers', None)
    session.pop('quiz_questions', None)
    
    return redirect(url_for('portalfejlesztes_net_ben.quiz'))

# All questions route (show all questions)
@portalfejlesztes_net_ben.route('/allquestions')
def allquestions():
    questions = parse_questions()

    return render_template('allquestions.html', questions=questions)
