from datetime import datetime, timedelta
from osinacore.models import *

class OnlineConnectionMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Call the view function or next middleware in the stack
        response = self.get_response(request)


        if request.user.is_authenticated and request.user.staffprofile:
            current_datetime = datetime.now()
            last_connection = Connection.objects.filter(user=request.user).order_by('-date').first()
            if not last_connection or last_connection.status != 'Online':
                Connection.objects.create(user=request.user, status='Online', date=current_datetime)
                new_status = Status.objects.create(
                    text='I am now online!',
                    date=datetime.now().date(),  # Getting the current date
                    time=datetime.now().strftime('%I:%M %p'), 
                    staff=request.user.staffprofile
                )


        return response
