import logging, threading
from flask import Flask
from flask_restful import Api
from werkzeug.serving import make_server
from context.Config import RESTAPI_BASE_URL, RESTAPI_SERVICE_PORT

logging.getLogger('werkzeug').setLevel(logging.WARNING)

BIND_ADDRESS = '0.0.0.0'
LOGGER = logging.getLogger(__name__)

class Server(threading.Thread):
    def __init__(self, host=BIND_ADDRESS, port=RESTAPI_SERVICE_PORT, base_url=RESTAPI_BASE_URL):
        threading.Thread.__init__(self, daemon=True)
        self.host = host
        self.port = port
        self.base_url = base_url
        self.srv = None
        self.ctx = None
        self.app = Flask(__name__)
        self.api = Api(self.app, prefix=self.base_url)

    def add_resource(self, resource, *urls, **kwargs):
        self.api.add_resource(resource, *urls, **kwargs)

    def run(self):
        self.srv = make_server(self.host, self.port, self.app, threaded=True)
        self.ctx = self.app.app_context()
        self.ctx.push()

        endpoint = 'http://{:s}:{:s}{:s}'.format(str(self.host), str(self.port), str(self.base_url))
        LOGGER.info('Listening on {:s}...'.format(str(endpoint)))
        self.srv.serve_forever()

    def shutdown(self):
        self.srv.shutdown()
