import logging, threading, time
from flask import Flask, request
from flask_restful import Api, Resource
from werkzeug.serving import make_server
from compute.Config import RESTAPI_BASE_URL, RESTAPI_SERVICE_PORT

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

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

def log_request(response):
    timestamp = time.strftime('[%Y-%b-%d %H:%M]')
    LOGGER.info('%s %s %s %s %s', timestamp, request.remote_addr, request.method, request.full_path, response.status)
    return response

class RestServer(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.app.after_request(log_request)
        self.api = Api(self.app, prefix=self.base_url)

    def add_resource(self, resource : 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()
