from pydoc_data.topics import topics
import pymongo
from flask import Flask, render_template, request, jsonify
from pymongo import MongoClient
from bson.objectid import ObjectId
from flask_cors import CORS
import os
from resources import aeg
from database.repository_base import RepositoryBase
from werkzeug.exceptions import HTTPException
import json
from datetime import datetime

path = os.getcwd()
parent = os.path.dirname(path)

app = Flask(__name__, template_folder=parent + '/frontend/public')

# Get database instance
db = RepositoryBase()

CORS(app)
if (db != None):
    print('MongoDB has been started.')


@app.route('/')
def home():
    return render_template('index.html')


#Upon quiz submission, access professor data in database and calculate results
@app.route('/api/quiz', methods=['POST', 'GET'])
def index():
    body = request.json
    question_id = str(body['id'])
    arg_student = body['answer'] 

    # Accessing prof answer from database
    try:
        prof_answer_data = db.find_one("question", {"id": int(body["id"])})

        if len(prof_answer_data) == 0:
            print("Error! Professor question could not be found")
            return "Error! Professor question could not be found", 404
    except BaseException as e:
        print("Error occurred during Professor answer lookup")
        return "Error occurred during Professor answer lookup", 500

    prof_answer = prof_answer_data['answer']

    result = aeg.results(arg_student, prof_answer, prof_answer_data, question_id)
    result["time"] = datetime.utcnow()  # Get the time of the result in UTC and set it to the result object

    # order of the function calls to get text classification solution

    result_insert_data = db.insert_one("results", result)
    result["_id"] = str(result_insert_data.inserted_id)  # get the ID of the result object in the db after inserting
    print(result)

    # print(aeg.format_data(0))

    return jsonify(result)


@app.route('/api/question', methods=['POST', 'GET'])
def question():
    try:
        if not request.data:
            return "Request is empty", 400
        request_data = request.json
        question_data = {
            "id": 0,
            "question": "",
            "answer": "",
            "format": "",
            "time_limit": "",
            "topics": {}
        }
        if request.method == 'GET':
            pass
        elif request.method == 'POST':
            # Check if the request has the required parameters
            if "question" not in request_data or "answer" not in request_data or "topics" not in request_data:
                return "Request contains malformed data", 400
            if not request_data["topics"]:
                return "Request contains malformed data", 400
            question_data["question"] = request_data["question"]
            question_data["answer"] = request_data["answer"]
            # Default the format to IRAC if it is not in the request
            question_data["format"] = request_data.get("format", "IRAC")
            # Default the time limit to 0 if it is not in the request or if it isn't an integer
            if str(request_data.get("time_limit", "")).isdigit():
                question_data["time_limit"] = int(request_data.get("time_limit", 0))
            else:
                question_data["time_limit"] = 0

            # Go through all the topics in the HTTP request
            for topic in request_data["topics"]:
                topic_data = request_data["topics"][topic]
                # Check if the topic data contains the sentence and the keywords
                if "sentence" not in topic_data or "keywords" not in topic_data:
                    break
                # Check if sentence or keywords are empty. If they are, the topic will be skipped
                if not topic_data["sentence"] or not topic_data["keywords"]:
                    break

                # Set the topic sentence and keywords. this is done so nothing extra gets put in the database
                question_data["topics"][topic] = {}
                question_data["topics"][topic]["sentence"] = []
                if isinstance(topic_data["sentence"], list):
                    question_data["topics"][topic]["sentence"] = topic_data["sentence"]
                elif isinstance(topic_data["sentence"], str):
                    question_data["topics"][topic]["sentence"].append(topic_data["sentence"])
                question_data["topics"][topic]["keywords"] = topic_data["keywords"]

            # Return an error if none of the topics are valid
            if not question_data["topics"]:
                return "Request contains malformed data", 400

            # Find the last question uploaded, and increment the ID by 1
            # This has to be done manually because Mongo does not support auto increment
            last_document = db.find_one("question", {}, sort=[('_id', pymongo.DESCENDING)])
            question_data["id"] = last_document["id"] + 1
            # Insert question data to the DB
            insert_data = db.insert_one("question", question_data)
            # Save resulting object ID to the question data object
            question_data["_id"] = str(insert_data.inserted_id)

            return question_data
    except HTTPException as e:
        return e
    except BaseException as e:
        print(e)
        return "Exception occurred while processing this request!", 500


if __name__ == '__main__':
    app.debug = True
    app.run(host="0.0.0.0", port=3001)
