from datetime import time
from flask import Flask, jsonify, request, session, redirect
from werkzeug.wrappers import response
from app import db
from uuid import uuid4
import pymongo
import xml.etree.ElementTree as ET
import xmltodict
import json

# class for QuestionBank which contains all the models needed in the routes section
class QuestionBank:

    # Upload a new QuestionBank
    # Due to the app using mongodb, uploading files is not possible.
    # Thus we opted for saving xmls as strings into MongoDB
    def new_questionbank(self):
        f = request.files.get('qbankxml')
        if session['user']['isProfessor']:
            tree = ET.parse(f)
            xml_data = tree.getroot()
            topic_list = []
            for x in xml_data:
                topic_list.append(x.text.rstrip())
            xmlstr_data = ET.tostring(xml_data, encoding='utf8', method='xml')
            xmlstr = xmlstr_data.decode("utf-8")
            qbank = {
                "_id": uuid4().hex,
                "professor_id": session['user']['_id'],
                "qbankName": request.form.get('qbankName'),
                "topicList": topic_list,
                "qbankXML": xmlstr
            }
            db.questionbank.insert_one(qbank)

            return jsonify(qbank), 201
        else:
            return jsonify({"Error": 'Forbidden action'}), 403

    # Searched and retrieve the questionbanks that a professor owns
    # In the future consider adding an array to the professors objects with the id of each question
    # That way we can do constant lookups on the DB. However right now it doesnt present a problem
    def get_questionbank(self):
        if session['user']['isProfessor']:
            qbank_lst = db.questionbank.find({"professor_id": session['user']['_id']})

        return list(qbank_lst)

    # Remove a questionbank based on an _id
    def remove_questionbank(self):
        if session['user']['isProfessor']:
            db.questionbank.find_one_and_delete({"_id": request.form.get('qbankID')})
    
    # get xml questions, turn into json and return
    # We used XML to store quesitons due to professor suggestions
    # However, it would seem that simply using JSON might be better in the long run.
    # Consider this in future development
    def get_question(self, topic_to_find):
        class_ = db.classes.find_one({"_id": request.args.get('class_id')})
        q_bank = db.questionbank.find_one({"_id": class_['selected_qb']})
        xml_string = q_bank['qbankXML']
        xmldict = xmltodict.parse(xml_string)

        for topic in xmldict['QuestionBank']['topic']:
            if topic_to_find.lower() == topic["#text"].lower():
                questions_list = json.dumps(topic["q"], indent=4)
        
        json_final = json.loads(questions_list) # this is to turn it into a proper json object instead of the json string

        return json_final
