# Copyright (c) 2014 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
from collections import namedtuple, OrderedDict
from flask import _request_ctx_stack

__author__ = 'shreyder'


LinkedScript = namedtuple("LinkedScript", ("url", "mime_type"))


class PageResourceRegistry(object):
    """Register resources like script files for later inclusion in pages."""

    @property
    def page_resources(self):
        """Page resources are attached to Flask's current request context."""
        ctx = _request_ctx_stack.top
        if not hasattr(ctx, "page_resources"):
            ctx.page_resources = namedtuple(
                "PageResources", ("script_files", "ready_scripts")
            )(OrderedDict(), list())
        return ctx.page_resources

    def link_script(self, url, mime_type="text/javascript"):
        """
        Link a script file using a URL.

        A particular URL will only be included once. Scripts are linked in the
        order they were added.
        """
        print("linked {}".format(url))
        self.page_resources.script_files[url] = LinkedScript(url, mime_type)

    def ready_script(self, script):
        """
        Register a script as jQuery onReady handler.

        The scripts will be wrapped in closure to prevent name clashes between
        variables.
        """
        self.page_resources.ready_scripts.append(script)

    def init_app(self, app):
        app.context_processor(lambda: {"page_resources": self.page_resources})


page_resources = PageResourceRegistry()

@@ -291,33 +291,8 @@
 ck%0A%0A
-__author__ = 'shreyder'%0A%0A
 %0ALin
@@ -352,16 +352,95 @@
 type%22))%0A
+PageResources = namedtuple(%22PageResources%22, (%22script_files%22, %22ready_scripts%22))%0A
 %0A%0Aclass 
@@ -790,100 +790,21 @@
 s = 
-namedtuple(%0A                %22PageResources%22, (%22script_files%22, %22ready_scripts%22)%0A            )
+PageResources
 (Ord
@@ -1075,16 +1075,22 @@
 ey were 
+first 
 added.%0A 
@@ -1104,47 +1104,8 @@
 %22%22%22%0A
-        print(%22linked %7B%7D%22.format(url))%0A
     
@@ -1186,16 +1186,23 @@
     def 
+append_
 ready_sc
@@ -1326,16 +1326,18 @@
 pped in 
+a 
 closure 

Improve page resources