"""
Tasks for running the server and seeing its configuration.

:copyright: Copyright 2013-2015, Dorian Pula <dorian.pula@amber-penguin-software.ca>
:license: AGPL v3+
"""

import pprint

import invoke as inv
import pexpect

import rookeries


@inv.task
def config():
    """Shows the current configuration of the Rookeries webapp."""
    rookeries_app = rookeries.make_rookeries_app()
    app_config = rookeries_app.config.items()
    pprint.pprint(sorted(app_config))


def run_debug_server(port):
    from werkzeug.debug import DebuggedApplication
    application = rookeries.make_rookeries_app()
    debug_app = DebuggedApplication(application, evalex=True)
    debug_app.app.run(port=port)


@inv.task
def run(port=5000):
    """Run server for debugging."""
    node_babel_watcher = None
    try:
        node_babel_watcher = pexpect.spawn('npm run watch', echo=True)
        run_debug_server(port)
    finally:
        if node_babel_watcher:
            node_babel_watcher.terminate()
