import sys
import json
import random
import base64
from flask import Flask, redirect, url_for, request, session, make_response, jsonify, send_from_directory
from flask import render_template
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import Integer, String, Column
from datetime import datetime
import uuid
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy import inspect
from sqlalchemy.orm import DeclarativeBase

random_order = True
# activate environment: cd C:\Users\Jan\Google Drive\Master Stuff\Code\SLAEForms Testing\.venv\Scripts\
# then this: activate

#SETUP--------------------------------------------------

#Set up sqlalchemy
class Base(DeclarativeBase):
  pass

db = SQLAlchemy(model_class=Base)

#create the app
app = Flask(__name__)
# configure the database, give it a path (it will be in the instances folder)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///database.db"
db.init_app(app)

#set the secret key (TODO change this for final deployment)
app.secret_key = b"29fe9e8edd407c5491d4f1c05632d9fa33e26ed8734a3f5e080ebac3772a555a"


#---------testing
#open the json file with the config
configfile = open("singleformconfig.json")
#convert it to dict
config = json.load(configfile)
configfile.close()
# get the questions:    Questions is a list that contains the keys of the dictionary
questions = list(config)


@app.route("/form", methods=["GET", "POST"])
def formpage():
    #user is not yet registered and should not be here
    if not "slaeform_user_id" in session:
        return redirect("/start")
    

    #TODO fill in code that determins at which question the user is
    print("form starts, the sessionorder rn:")
    print(session["question_order"])
    if not session["question_order"]:
        print("---------------question order is empty------------")
        return redirect("/data") 
        
    print("pop the first element")
    current_question = session["question_order"].pop(0)
    session["current_question"] = current_question
    print(current_question)
    print("the new sessionorder rn:")
    print(session["question_order"])
    session["question_order"] = session["question_order"]
    print("has this changed sth?:")
    print(session["question_order"])

    

    return render_template(
        "layout2.html",
        config=config,
        current_question = current_question,
        videotype=config[current_question]["type"],
        video_url= config[current_question]["video1"],
        blocks = config[current_question]["blocks"]
    )