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

# Define the Blueprint for the halozatok quiz
szamitogepek_mukodese = Blueprint(
    'szamitogepek_mukodese',  # Blueprint name
    __name__,
    template_folder='./templates'  # Path to templates
)

preguntas = ['templates/uni/subjects/szamitogepek_mukodese/szgm_kerdessor.txt']

def parse_questions():
    questions = []
    lines = []
    for pregunta in preguntas:
        with open(pregunta, 'r', encoding='utf-8') as f:
            lines.extend(f.readlines())
    
    for line in range(0, len(lines)-1, 2):
        questions.append({
                'question': lines[line].strip(),
                'answer': lines[line + 1].strip()
            })

    return questions

# Quiz Route
@szamitogepek_mukodese.route('/')
@szamitogepek_mukodese.route('/quiz', methods=['GET', 'POST'])
def quiz():
    if 'quiz_questions' not in session:
        questions = parse_questions()
        halozatok_questions = random.sample(questions, 20)
        session['quiz_questions'] = halozatok_questions
        session['question_index'] = 0
        session['answers'] = []
    else:
        halozatok_questions = session['quiz_questions']

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

    if question_index >= len(halozatok_questions):
        return redirect(url_for('szamitogepek_mukodese.result'))

    current_question = halozatok_questions[question_index]

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

# Submit Answer Route
@szamitogepek_mukodese.route('/submit_answer', methods=['POST'])
def submit_answer():
    user_answers = request.form.get('answer')
    question_index = int(request.form.get('question_index'))

    if 'answers' not in session:
        session['answers'] = []

    answers = session.get('answers')
    answers.append(user_answers)
    session['answers'] = answers

    question_index += 1
    session['question_index'] = question_index
    
    return redirect(url_for('szamitogepek_mukodese.quiz'))

# Result Route
@szamitogepek_mukodese.route('/result')
def result():
    halozatok_questions = session['quiz_questions']
    answers = session['answers']
    score = 0
    mistakes = []

    for i in range(len(answers)):
        if halozatok_questions[i]['answer'] == answers[i]:
            score += 1
        else:
            mistakes.append({
                'question': halozatok_questions[i]['question'],
                'answer': 'True' if answers[i] == 'I' else 'False',
                'correct': 'True' if halozatok_questions[i]['answer'] == 'I' else 'False' 
            })
        halozatok_questions[i]['answer'] = 'True' if halozatok_questions[i]['answer'] == 'I' else 'False'

    return render_template('szgm_result.html', score=score, total=len(halozatok_questions), mistakes=mistakes, halozatok_questions=halozatok_questions)

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

# All Questions Route
@szamitogepek_mukodese.route('/allquestions')
def allquestions():
    questions = parse_questions()
    for i in questions:
        i['answer'] = 'True' if i['answer'] == 'I' else 'False'
    return render_template('szgm_allquestions.html', questions=questions)
