# -*- mode: python; coding: utf-8 -*-
# Copyright 2015 Peter Williams <peter@newton.cx> and collaborators.
# Licensed under the MIT License.

"""dashboard - a Jupyter extension

This is a Jupyter Notebook Server extension that adds a dashboard pane to the
tree that has some shortcuts that I find useful.

"""
from __future__ import absolute_import, division, print_function, unicode_literals

import os.path
from tornado import web
from notebook.utils import url_path_join as ujoin
from notebook.tree.handlers import TreeHandler


webpath = '/extensions/pwkit-dashboard'
fspath = os.path.dirname (__file__)


def load_jupyter_server_extension (nbapp):
    """Tornado doesn't seem to supply us with a mechanism to *override* an
    already-registered handler; its infrastructure is particularly weak if
    you'd like to potentially *chain* overrides of a handler. Therefore we do
    some hacky poking around in places that we probably ought to stay out of.

    """
    webapp = nbapp.web_app
    hosts_to_add = set ()

    for host_regex, urlspecs in webapp.handlers:
        gotany = False

        for urlspec in urlspecs:
            if issubclass (urlspec.handler_class, TreeHandler):
                scripts = urlspec.kwargs.setdefault ('extra_scripts', [])
                scripts.append (ujoin (webapp.settings['base_url'], webpath, 'dashboard.js'))
                gotany = True

        if gotany:
            hosts_to_add.add (host_regex.pattern)

    for host_regex in hosts_to_add:
        webapp.add_handlers (host_regex, [
            (ujoin (webapp.settings['base_url'], webpath, r'(.*\.js)'), web.StaticFileHandler, {'path': fspath}),
        ])
