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

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

preguntas = ['templates/uni/subjects/vallalati_informacios_rendszerek/vir_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()
            })
    
    print(questions[1])
    print(questions[2])
    print(questions[3])

    return questions

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

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

    if question_index >= len(vir_questions):
        return redirect(url_for('vallalati_informacios_rendszerek.result'))

    current_question = vir_questions[question_index]

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

# Submit Answer Route
@vallalati_informacios_rendszerek.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('vallalati_informacios_rendszerek.quiz'))

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

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

    return render_template('vir_result.html', score=score, total=len(vir_questions), mistakes=mistakes, vir_questions=vir_questions)

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

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