from flask import Flask, jsonify, request, session, redirect
from passlib.hash import pbkdf2_sha256
import pymongo
from app import db
from Students.models import Student
from Professors.models import Professor
from uuid import uuid4

# class that handles the creation of users (Students and Professors alike)
class User:

    #User log in
    def login(self):
        user = db.users.find_one({
            "email": request.form.get('email')
        })

        if user and pbkdf2_sha256.verify(request.form.get('password'), user['password']):
            self.start_session(user)
            return jsonify({"Success": "Successful login"}), 201
        
        return jsonify({"error": 'Invalid login credentials'}), 401

    # Start the session for the user
    def start_session(self, user):
        del user['password']
        session['logged_in'] = True
        session['user'] = user

    # User signout
    def signout(self):
        session.clear()
        return redirect('/')

    # User signup as well as professor and student assignment
    def signup(self):

        user = {
            "_id": uuid4().hex,
            "lastName": request.form.get('lastName'),
            "firstName": request.form.get('firstName'),
            "email": request.form.get('email'),
            "password": request.form.get('password'),
            "isProfessor": False
        }

        # Encrypt the password
        user['password'] = pbkdf2_sha256.encrypt(user['password'])
        
        users_db = db['users']
        try:
            users_db.insert_one(user)
            self.start_session(user)
        except pymongo.errors.DuplicateKeyError as e:
            return jsonify({"Error": "Email already exists on records"}), 400
        if user['isProfessor']:
            print("Creating Professor Accc")
            Professor().new_professor(user)
        else:
            print("Creating student")
            Student().new_student(user)
        return jsonify({"Success": "Account created"}), 201
