# -*- coding: utf-8 -*-
import gunicorn.app.base


class GunicornApp(gunicorn.app.base.BaseApplication):
    __slots__ = ('flask_app', 'host', 'port', 'workers', 'log', 'loglevel')

    def __init__(self, flask_app, host, port, workers, log='__name__', loglevel=None):
        self.flask_app = flask_app
        self.host = host
        self.port = port
        self.workers = workers
        self.loglevel = loglevel
        self.errorlog = log + '-main'
        self.accesslog = log + '-access'
        super(GunicornApp, self).__init__()

    def load_config(self):
        self.cfg.set('workers', self.workers)
        bind_pattern = '[{}]:{}' if ':' in self.host else '{}:{}'
        self.cfg.set('bind', bind_pattern.format(self.host, self.port))
        if self.errorlog is not None:
            self.cfg.set('errorlog', self.errorlog)
        if self.accesslog is not None:
            self.cfg.set('accesslog', self.accesslog)
        if self.loglevel is not None:
            self.cfg.set('loglevel', self.loglevel)
        self.cfg.set('worker_class', 'gunicorn.workers.gthread.ThreadWorker')

    def load(self):
        return self.flask_app

    def run(self):
        # Start app
        super(GunicornApp, self).run()
