from django.conf import settings
from django.db import signals
from django.dispatch import dispatcher
from django.template import loader

class SQLTracker(object):
    def __init__(self):
        self.queries = []

    def add(self, unbound, params, bound, runtime):
        self.queries.append({'unbound': unbound, 'params': params, 'bound': bound, 'runtime': runtime})


class SQLTrackerMiddleware(object):
    def __init__(self, *args, **kwargs):
        print 'SQLTrackerMiddleware being inited'
    
    def process_request(self, request):
        # FIXME: I know this is bad, but I'm not sure where else to put it.
        request.sql_tracker = SQLTracker()
        def track_query(sender, *args, **kwargs):
            display_sql = sender.db.ops.last_executed_query(sender, kwargs['sql'], kwargs['params'])
            request.sql_tracker.add(kwargs['sql'], kwargs['params'], display_sql, kwargs['time'])
        # weak=False is necessary for this to bind here.
        dispatcher.connect(track_query, signal=signals.query_execute, weak=False)

    def create_debug_sql_output(self, request, response):
        """ Generates SQL output for debugging.
        
        Separate from process_response so that it is easier to override without
        worrying about the details of attaching it to the response.
         
        """
        return loader.render_to_string('debug_sql.html', {'queries': request.sql_tracker.queries})

    def process_response(self, request, response):
        if settings.DEBUG:
            # Prevent it from being sent with any non-default content-encodings
            # (anything but plaintext).
            if not response.has_header('Content-Encoding'):
                # FIXME: There's still all sorts of reasons this could fail, let it
                # do so gracefully.
                try:
                    response.content += self.create_debug_sql_output(request, response)
                except:
                    pass
        return response
