import argparse
import logging
import pyuwsgi

from flask import Flask

from load.projects.validator.src.api import bp


def create_app():

    app = Flask(__name__)
    app.config.from_envvar('APPLICATION_SETTINGS')
    app.register_blueprint(bp)

    logto = app.config['LOGTO']
    file_handler = logging.FileHandler(logto)
    file_handler.setLevel(logging.DEBUG if app.config["DEBUG"] else logging.INFO)
    formatter = logging.Formatter("%(asctime)s\t%(levelname)s\t%(message)s")
    file_handler.setFormatter(formatter)

    logger = app.logger
    logger.addHandler(file_handler)
    logging.info("Started logging to: %s", logto)

    return app


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-w', '--proc_num', default=8, help='WSGI_PROC_NUM')
    parser.add_argument('-p', '--port', type=int, default=80, help='server port')
    params, _ = parser.parse_known_args()

    pyuwsgi.run([
        '--http', '[::]:{}'.format(params.port),
        '--module', 'load.projects.validator.bin.main:create_app()',
        '--log-master',
        '--processes', '{num}'.format(num=params.proc_num),
        '--enable-threads'
    ])
