from pyramid_debugtoolbar.panels import DebugPanel
from pyramid_debugtoolbar.utils import format_sql as ppq


def format_sql(query):
    query = ppq(query)
    query = query.replace(',', ',<br/>')
    query = query.replace('JOIN', '<br/>&nbsp;JOIN')
    return query


class StrawDebugPanel(DebugPanel):
    """
    Panel that displays the SQL generated by SQLAlchemy and the time, memory
     and calling function.
    """
    name = 'straw'
    template = 'pyramid_straw:templates/straw_debugtoolbar.mako'
    title = 'SQLAlchemy Profiler'
    nav_title = 'Straw'

    def __init__(self, request):
        super(StrawDebugPanel, self).__init__(request)
        self.queries = request.straw_data = []

    @property
    def has_content(self):
        if self.queries:
            return True
        else:
            return False

    @property
    def nav_subtitle(self):
        if self.queries:
            cursor_queries = filter(lambda x: x['type'] == 'cursor', self.queries)  # noqa
            return "{} ({:.3f}ms)".format(
                len(self.queries),
                sum(map(lambda x: x['duration'], cursor_queries))
            )

    def render_vars(self, request):
        return {
            'queries': self.queries,
            'format_sql': format_sql,
            'route_url': request.route_url,
            'static_path': '/_debug_toolbar/straw/static'  # TOOO: fix this
        }


def includeme(config):
    config.include('pyramid_straw.panel.debugpanel_wsgi_app')
    config.registry.settings['debugtoolbar.panels'].append(StrawDebugPanel)
