from flask import session
from datetime import datetime, timedelta
from threading import Thread
import time

def check_session_timeout():
    timeout = timedelta(seconds=10)
    while True:
        # Get the last access time of the session
        last_access_time = session.get('_accessed', None)
        if last_access_time is not None and datetime.now() - last_access_time > timeout:
            # If the session has timed out, log the user out and remove the session data
            user = auth.find_one({"username": session['username']})
            print(user['_id'])
            session_manager.destroy_session(user['_id'])
            session.pop('username', None)
            session.clear()
            print("Session Cleared")
        # Wait for some time before checking the session timeout again
        time.sleep(1)

def start_session_timeout_thread():
    print("This session timeout thread")
    timeout_thread = Thread(target=check_session_timeout)
    timeout_thread.start()
