from time import time

from django.contrib.sites.models import Site
from django.core.mail import mail_admins

class StatsMiddleware(object):

    """ If the soft limit is exceeded then StatsMiddleware will send an email to the admin with details of the request """
    SOFT_LIMIT_SECONDS = 5.0
    
    SOFT_LIMIT_SUBJECT = "Soft Timeout: %s"
    SOFT_LIMIT_MESSAGE = \
"""The soft timeout (%f secs) has been exceeded.
Time: %f
URL: %s
"""

    # fixme: Implement hard limit?
    #        Strategy would probably be to spawn a monitor thread which checks that the request has finished in time
    #        which raises an exception along the lines of: http://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python
    #        Maybe better to leave hard limit of mod_wsgi ?
        
    def process_view(self, request, view_func, view_args, view_kwargs):

        start = time()
        response = view_func(request, *view_args, **view_kwargs)
        elapsed = time() - start
        
        if elapsed > StatsMiddleware.SOFT_LIMIT_SECONDS:
            site = Site.objects.get_current()
            url = 'http://%s%s' % (site.domain, request.path)
            subject = StatsMiddleware.SOFT_LIMIT_SUBJECT % url
            message = StatsMiddleware.SOFT_LIMIT_MESSAGE % (StatsMiddleware.SOFT_LIMIT_SECONDS, elapsed, url)
            mail_admins(subject, message, True)
        return response

