# -*- coding: utf-8 -*-
import os
import gunicorn.app.base
from datacloud.score_api.server import app


class GunicornApp(gunicorn.app.base.BaseApplication):
    def __init__(self, flask_app, host, port, workers, timeout):
        self.flask_app = flask_app
        self.host = host
        self.port = port
        self.workers = workers
        self.timeout = timeout
        super(GunicornApp, self).__init__()

    def load_config(self):
        self.cfg.set('workers', self.workers)
        self.cfg.set('bind', '{}:{}'.format(self.host, self.port))
        self.cfg.set('timeout', self.timeout)

    def load(self):
        return self.flask_app


def main(port=None, workers=None, is_old_yt_app=None, timeout=None):
    print('Start datacloud score api')

    if port is None:
        port = int(os.environ.get('SCORE_API_PORT', 80))
    if workers is None:
        workers = int(os.environ.get('SCORE_API_WORKERS', 6))
    if is_old_yt_app is None:
        is_old_yt_app = bool(os.environ.get('SCORE_API_IS_OLD_YT_APP', False))
    if timeout is None:
        timeout = int(os.environ.get('SCORE_API_TIMEOUT', 30))
    if is_old_yt_app:
        print('Start old version YT app')
        app_func = app.main
    else:
        app_func = app.ydb_main

    print('workers: {}, port: {}'.format(workers, port))

    _app = GunicornApp(
        app_func(),
        host='[::]',
        port=port,
        workers=workers,
        timeout=timeout
    )
    _app.run()


if __name__ == '__main__':
    main()
