from flask import Flask, render_template, request, session, redirect
from functools import wraps
from pymongo import MongoClient
import os
from dotenv import load_dotenv
load_dotenv()

# FLASK APPLICATION
app = Flask(__name__)

# Make sure to add the secret key
# You can use any random string Ideally just  import os and copy os.urandom(16)
app.secret_key = os.getenv('SECRET_KEY')        

# Here Connect to the Database
client = MongoClient(os.getenv('MONGO_URI'))
db = client["MorningBytesDB"]

#Decorator to use when user req to be logged in
def login_required(f):
    @wraps(f)
    def wrap(*arg, **kwargs):
        if 'logged_in' in session:
            return f(*arg, **kwargs)
        else:
            return redirect('/')
    return wrap

#Decorator to use when user req to not be logged in
def not_login_required(f):
    @wraps(f)
    def wrap(*arg, **kwargs):
        if 'logged_in' in session:
            return redirect('/')
        else:
            return f(*arg, **kwargs)
    return wrap

# Import the New routes HERE
from Users import routes
from Classes import routes
from Classes.models import Class
from MBytes.models import MBytes
from MBytes import routes
from QuestionBank import routes
from QuestionBank.models import QuestionBank

#Signup Route
@app.route('/signup', methods=['GET'])
@not_login_required
def signup():
    return render_template("create_account.html")

#Dashboard Route
@app.route('/dashboard', methods=['GET'])
@login_required
def dashboard():
    classes_lst = list(Class().get_classes())
    ready_bytes, questionbanks = [], []
    #Divide into professors and Students
    if not session['user']['isProfessor']:
        ready_bytes = MBytes().get_ready_bytes()
    else:
        questionbanks = QuestionBank().get_questionbank()
        for c in classes_lst:
            mbytes_days = []
            for i in range(7):
                if i in c['MBytesDays']:
                    mbytes_days.append('checked')
                else:
                    mbytes_days.append('')
            c['MBytesDays'] = mbytes_days
    return render_template("dashboard.html",list_of_classes = classes_lst, ready_bytes= ready_bytes, qbs = questionbanks )

#Route for log in page
@app.route('/login', methods=['GET'])
@not_login_required
def login():
    return render_template("login.html")

#Home Route
@app.route('/')
def home():
    return render_template('home.html')