"""Setup pyramid wsgi app."""
from pyramid.config import Configurator
from pyramid_zodbconn import get_connection
from substanced.evolution import mark_unfinished_as_finished as markunf
import transaction

from adhocracy_core.authentication import TokenHeaderAuthenticationPolicy
from adhocracy_core.authorization import RoleACLAuthorizationPolicy
from adhocracy_core.resources.root import IRootPool
from adhocracy_core.resources.principal import groups_and_roles_finder


def root_factory(request, t=transaction, connection=None,
                 mark_unfinished_as_finished=False):
    """ A function which can be used as a Pyramid ``root_factory``.

    It accepts a request and returns an instance of the ``Root`` content type.

    """
    # FIXME: Fix substanced bug: mark_unfinished_as_finished keyword
    # is not working.
    # Don't get the root object if the request already has one.
    # Workaround to make the subrequests in adhocracy_core.rest.batchview work.
    if getattr(request, 'root', False):
        return request.root
    if connection is None:
        connection = get_connection(request)
    zodb_root = connection.root()
    if 'app_root' not in zodb_root:
        registry = request.registry
        app_root = registry.content.create(IRootPool.__identifier__,
                                           registry=request.registry)
        zodb_root['app_root'] = app_root
        t.savepoint()  # give app_root a _p_jar
        if mark_unfinished_as_finished:
            markunf(app_root, registry, t)
        t.commit()
    add_after_commit_hooks(request)
    return zodb_root['app_root']


def add_after_commit_hooks(request):
    """Add after commit hook to notify the websocket server."""
    # FIXME this is a quick hack
    from adhocracy_core.websockets.client import \
        send_messages_after_commit_hook
    from adhocracy_core.resources.subscriber import\
        clear_transaction_changelog_after_commit_hook
    current_transaction = transaction.get()
    registry = request.registry
    current_transaction.addAfterCommitHook(send_messages_after_commit_hook,
                                           args=(registry,))
    current_transaction.addAfterCommitHook(
        clear_transaction_changelog_after_commit_hook, args=(registry,))


def includeme(config):
    """Setup basic adhocracy."""
    settings = config.registry.settings
    config.include('pyramid_zodbconn')
    config.include('pyramid_exclog')
    config.include('pyramid_mako')
    config.hook_zca()  # enable global adapter lookup (used by adhocracy.utils)
    authz_policy = RoleACLAuthorizationPolicy()
    config.hook_zca()  # global adapter lookup (used by adhocracy_core.utils)
    authz_policy = RoleACLAuthorizationPolicy()
    config.set_authorization_policy(authz_policy)
    authn_secret = settings.get('substanced.secret')
    authn_timeout = 60 * 60 * 24 * 30
    authn_policy = TokenHeaderAuthenticationPolicy(
        authn_secret,
        groupfinder=groups_and_roles_finder,
        timeout=authn_timeout)
    config.set_authentication_policy(authn_policy)
    config.include('.authentication')
    config.include('.evolution')
    config.include('.events')
    config.include('.registry')
    config.include('.graph')
    config.include('.catalog')
    config.include('.messaging')
    config.include('.sheets')
    config.include('.resources.pool')
    config.include('.resources.root')
    config.include('.resources.tag')
    config.include('.resources.comment')
    config.include('.resources.principal')
    config.include('.resources.rate')
    config.include('.resources.subscriber')
    config.include('.websockets')
    config.include('.rest')


def main(global_config, **settings):
    """ Return a Pyramid WSGI application. """
    config = Configurator(settings=settings, root_factory=root_factory)
    includeme(config)
    return config.make_wsgi_app()

@@ -127,63 +127,27 @@
 ced.
-evolution import mark_unfinished_as_finished as markunf
+db import RootAdded
 %0Aimp
@@ -458,342 +458,81 @@
 uest
-, t=transaction, connection=None,%0A                 mark_unfinished_as_finished=False):%0A    %22%22%22 A function which can be used as a Pyramid %60%60root_factory%60%60.%0A%0A    It accepts a request and returns an instance of the %60%60Root%60%60 content type.%0A%0A    %22%22%22%0A    # FIXME: Fix substanced bug: mark_unfinished_as_finished keyword%0A    # is not working.
+):%0A    %22%22%22 A function which can be used as a Pyramid %60%60root_factory%60%60.%22%22%22
 %0A   
@@ -744,39 +744,8 @@
 oot%0A
-    if connection is None:%0A    
     
@@ -777,24 +777,24 @@
 on(request)%0A
+
     zodb_roo
@@ -1076,16 +1076,26 @@
        t
+ransaction
 .savepoi
@@ -1137,81 +1137,43 @@
     
-if mark_unfinished_as_finished:%0A            markunf(app_root, registry, t
+registry.notify(RootAdded(app_root)
 )%0A  
@@ -1179,16 +1179,26 @@
        t
+ransaction
 .commit(
@@ -2733,24 +2733,60 @@
 thn_policy)%0A
+    config.include('substanced.db')%0A
     config.i
@@ -3554,22 +3554,21 @@
 ig)%0A    
-return
+app =
  config.
@@ -3583,8 +3583,23 @@
 i_app()%0A
+    return app%0A

cleanup root_factory