#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import click
import flask

from flask_migrate.cli import db as cli_db
from flask.cli import FlaskGroup

from saas.tools.abcd.app.extract_resources import load_and_write_resources
from saas.tools.abcd.app.app import prepare_flask_app
from saas.tools.abcd.app.gunicorn import GunicornApp
from saas.tools.abcd.app.prepare_logging import prepare_logging


# Arcadia resources extraction
load_and_write_resources('migrations')

app = flask.Flask(__name__)

# Cli
cli = FlaskGroup(create_app=lambda: app)


# Choices
@cli.command(help='Run application in gunicorn mode for production usage')
@click.option('--env', type=click.Choice(['testing', 'production']),
              help='Service installation type testing or production', default='production')
@click.option('--tvm/--no-tvm', default=True)
@click.option('--host', help='Service hostname', default='localhost')
@click.option('--port', help='Service port', default=5000)
@click.option('--workers', help='Gunicorn workers count', default=3)
@click.option('--logfile', default='common-log')
@click.option('--debug/--no-debug', default=False)
def gunicorn(host, port, workers, env, tvm, logfile=None, debug=False):
    app.debug = debug
    updated_app = prepare_flask_app(app=app, env_type=env, tvm_enable=tvm)
    loglevel = 'info'
    if debug:
        loglevel = 'debug'
    prepare_logging(loglevel.upper())

    gi_app = GunicornApp(updated_app, host=host, port=port, workers=workers, loglevel=loglevel,
                         log=logfile)
    gi_app.run()


def main():
    prepare_flask_app(app=app)
    cli.add_command(cli_db)
    cli()


if __name__ == '__main__':
    main()

