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 sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.dialects.postgresql import UUID
from datetime import datetime
import uuid
from sqlalchemy.exc import SQLAlchemyError




random_order = True

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

#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 = SQLAlchemy(app)

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


#--------temporär der code für dict to db test
database_schema = {
    "table_name": "userstest",
    "id": {"type": "integer", "nullable": False},
    "username": {"type": "string", "nullable": False,  "size": 20},
    "age": {"type": "integer", "nullable": True}
}

tablename = database_schema["table_name"].capitalize()

# test function to create tables from dicts
def create_model_class(schema):
    class_name = schema["table_name"].capitalize()

    # Define class attributes dynamically
    attributes = {"__tablename__": schema["table_name"]}

    attributes["uid"] = Column(db.UUID(as_uuid=True), primary_key=True, nullable=False)


    for column_name, column_info in schema.items():
        if column_name != "table_name":
            if column_info["type"] == "integer":
                column_type = Integer
            elif column_info["type"] == "string":
                column_type = String(column_info["size"])

            attributes[column_name] = Column(column_type, nullable=column_info["nullable"])

    # Create the model class
    return type(class_name, (db.Model,), attributes)

print("creating the userstest table")
customtable = create_model_class(database_schema)
try:
    with app.app_context():
        print("try to create tables")
        db.create_all()
except SQLAlchemyError as e:
    print("Error occurred during database creation:", str(e))

@app.route("/customsendtest", methods=["POST"])
def customsendtest():
    # Extract form data
    form_data = request.form

    # Create a new instance of the dynamically generated model
    new_user = customtable()

    # Assign form data to model attributes
    for key, value in form_data.items():
        if hasattr(new_user, key):
            setattr(new_user, key, value)
    new_id = uuid.uuid4()
    setattr(new_user, "uid",new_id)

    # Add new user to the database session and commit changes
    try:
        #print("new idea: {new_id} ".format(new_id=new_id))
        db.session.add(new_user)
        db.session.commit()
        return 'Data submitted successfully!'
    except SQLAlchemyError as e:
            print("Error occurred during database commit:", str(e))
            return 'Data not submitted successfully!'


@app.route("/customsend/<inputid>", methods=["POST"])
def customsend():

    session_user_id = session["slaeform_user_id"]
    likert_score = request.form["likertscale"]
    text_input = request.form["feedback"]
    question_title = session["current_question"]
    new_id = uuid.uuid4()
    date = datetime.today()
    print("new idea: {new_id} ".format(new_id=new_id))
    new_response = Response(id=new_id,user_id = session_user_id, question_title = question_title,likert_result = likert_score,notes = text_input, date_created = date)
        
    try:
        db.session.add(new_response)
        db.session.commit()
        return redirect("/form")
    except:
            return "There was a problem while adding the response to the Database"


# End testing-------------------------------------



# create the model for the response table
class Response(db.Model):
    id = db.Column(db.UUID(as_uuid=True), primary_key=True, nullable=False)
    user_id = db.Column(db.UUID(as_uuid=True), nullable=False)
    question_title = db.Column(db.String(30))
    likert_result = db.Column(db.Integer, nullable=False)
    notes = db.Column(db.String(200))
    date_created = db.Column(db.DateTime)
    def __repr__(self) -> str:
        return "<Response %r>" % self.id