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

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

import pprint

import invoke as inv

import rookeries


@inv.task
def config(ctx):
    """
    Shows the current configuration of the Rookeries webapp.

    :param ctx: Context of the invoke task.
    """
    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(ctx, port=5000, debugging=False):
    """
    Run the API app in a server.
    By default this runs a production uWSGI server.

    :param ctx: Context of the invoke task.
    :param port: The port to run the API app on.  5000 by default.
    :param debugging: Flag to switch to running a debug server.
    """
    if debugging:
        # TODO: Change nature of debugging to use uwsgi server but fewer workers and longer timeouts, etc.
        run_debug_server(port)
    else:
        inv.run(f'uwsgi --http :{port} --master --processes 4 --module "rookeries:make_rookeries_app()"')
