import threading
import time
import schedule
import datetime
import pymongo
from random import random
from datetime import timedelta
import smtplib
from email.message import EmailMessage

#TODO crosslink the students id between the , students for time, users for email, classroster for classes

db_client = pymongo.MongoClient(URI)
db = db_client["MorningBytesDB"]

students_collection = db["students"]
classroster_collection = db["classroster"]
classes_collection = db["classes"]
users_collection = db["users"]

#print(config('EMAIL_PASSWORD'))

def job():
    print("entered")
    time = f"{datetime.time(10):%I:%M}"
    students = get_students(time)

    for student in students:
        print(student)
        classes = get_classes(student["_id"])
        send_email(student,classes)


def send_email(student, classes):
    filters = {"_id": student["_id"]}
    desired_data = {"_id": 1, "email": 1}
    studentEmail = users_collection.find_one(filters, desired_data)

    greeting = "Hello, " + student["firstName"] +  "! Here are your Morning Bytes for the " + " course!\n"

    # #test email credentials
    # password = config('EMAIL_PASSWORD')
    #
    # #login to sender
    # sender_email = "morningbytes.test@gmail.com"
    # server = smtplib.SMTP('smtp.gmail.com', 587)
    # server.starttls()
    # server.login(sender_email,password)

    #message to send
    message = EmailMessage()
    message.set_content(greeting)
    message['Subject'] = 'Morning Bytes'
    message['From'] = "morningbytes.test@gmail.com"
    message['To'] = studentEmail["email"]
    #server.send_message(message)
    print("Email sent.")
    print(message)

def get_classes(class_id):
    filters = {"_id": class_id}
    desired_data = {"className": 1}
    classesList = classes_collection.aggregate(
        [{"$match": filters}, {"$sample": {"size": 3}}, {"$project": desired_data}])

    classArray = []

    for i in classesList:
        classArray.append(i["className"])

    return classArray

def get_students(time):
    print("get students enter")
    filters = {"reminderTime": time}
    desired_data = {"_id": 1,"firstName": 1, "lastName": 1}
    students = students_collection.find(filters, desired_data)

    return students

# Function wrapper that will simply create a thread and run a function in said thread
def run_threaded(job_func, time_):
    thread_name = str(datetime.datetime.now())
    job_thread = threading.Thread(target=job_func, args=(time_,))
    job_thread.setName("Thread-" + thread_name)
    job_thread.start()

# Initiate time delta at 00:00:00
t = timedelta()

# start the schedulers for the 288 5-min timeslots
# Somewhat of an overhead but might help later on
# loop on all times in 5 min intervals
while t != timedelta(days=1):
    # modify time for correct format
    modified_time = str(t)[:-3]
    if len(modified_time) == 4:
        modified_time = '0' + modified_time

    # schedule a task for each 5 min interval
    schedule.every().day.at(modified_time).do(run_threaded, job, modified_time)
    t += timedelta(minutes=1)

print("Scheduled succesfully, entering loop")
while 1:
    date_and_time = str(datetime.datetime.now())
    print("Attempted to run at: " + date_and_time)
    schedule.run_pending()
    time.sleep(10)

print("made it to the bottom")
