from datetime import time
from flask import Flask, jsonify, request, session, redirect
from app import db
from uuid import uuid4
import pymongo

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

    #Create new Class in the DB
    def new_class(self):
        if session['user']['isProfessor']:
            days = []
            for day in range(7):
                if request.form.get(str(day)):
                    days.append(day)
            if len(days) == 0:
                return jsonify({"Error": 'Missing Morning Bytes Days'}), 403
            _class = {
                "_id": uuid4().hex,
                "professor_id": session['user']['_id'],
                "classCode": uuid4().hex[0:7],
                "className": request.form.get('className'), 
                "classStartDate": request.form.get('classStartDate'),
                "classEndDate": request.form.get('classEndDate'),
                "classDescription": request.form.get('classDescription'),
                "MBytesDays": days
            }
            db.classes.insert_one(_class)

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

    #Change an existing class in the DB
    def update_class(self):
        if request.form.get('questionBank') == "-1":
            return jsonify('success'), 201
        if session['user']['isProfessor']:
            new_days = [x for x in range(7) if str(x) in request.form]
            topics = db.questionbank.find_one({'_id': request.form.get('questionBank')})['topicList']
            db.classes.update_one({'_id':request.form.get('class_id'), "professor_id": session['user']['_id']},{'$set':{'selected_qb':request.form.get('questionBank'),'MBytesDays':new_days,'currentTopic':topics[0]}})
            return jsonify('success'), 201

    #Change the current topic of a class AKA the current week/content from the QuestionBank for the morning bytes
    def update_topic(self):
        if session['user']['isProfessor']:
            db.classes.update_one({'_id':request.form.get('class_id'), "professor_id": session['user']['_id']},{'$set':{'currentTopic':request.form.get('new_topic')}})
            return jsonify('success'), 201
    #As a student Join a new class
    def join_class(self):
        if 'logged_in' in session and not session['user']['isProfessor']:
            _class = db.classes.find_one({"classCode": request.form.get('given_code').lower()})
            if _class:
                class_roster ={
                    "_id": uuid4().hex,
                    "classes_id": _class['_id'],
                    "student_id": session['user']['_id']
                }
                try:
                    db.classroster.insert_one(class_roster)
                    return jsonify({"Success": 'Successfully enrolled in the class'}), 201
                except pymongo.errors.DuplicateKeyError as e:
                    return jsonify({"Error": "Email already exists on records"}), 400
            else:
                return jsonify({"Error": 'Class Code not found'}), 404
    #Get all the classes that a professor owns or get all the classes that a student is enrolled in
    def get_classes(self):
        if session['user']['isProfessor']:
            classes_lst = db.classes.find({"professor_id": session['user']['_id']})
        else:
            classes_lst =  db.classroster.find({"student_id": session['user']['_id']})
            final_lst = []
            for c in classes_lst:
                current = db.classes.find_one({"_id":c['classes_id']})
                final_lst.append(current)
            classes_lst = final_lst
        return classes_lst

    #Get the current topic for morning bytes
    def get_topic(self, class_id):
        return db.classes.find_one({'_id': class_id})['currentTopic']

    #Delete an existing Class from the DB
    def delete_class(self):
        # TODO add logic to check that the professor logged in is the owner of the class
        if session['user']['isProfessor']:
            db.classes.find_one_and_delete({"_id": request.form.get('class_id')})
            return jsonify({"Success": 'Successfully Deleted the class'}), 201