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

:copyright: Copyright 2013-2017, 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))


@inv.task
def prepare_assets(ctx):
    ctx.run('npm run build', echo=True, pty=True)


@inv.task
def run_webpack_server(ctx):
    ctx.run('npm run dev-server', echo=True, pty=True)


@inv.task
def wait(ctx, timeout=10):
    ctx.run(f'dockerize -wait http://rookeries:5000/status -timeout {timeout}s')


@inv.task(prepare_assets)
def run(ctx, port=5000, dev_mode=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.
    """

    autoreload_flag = '' if not dev_mode else '--py-autoreload 1'

    uwsgi_cmd = ' '.join([
        'uwsgi',
        f'--http :{port}',
        '--master',
        '--processes 4',
        autoreload_flag,
        '--module "rookeries:make_rookeries_app()"',
    ])

    ctx.run(uwsgi_cmd, echo=True, pty=True)
