# Copyright 2021-2023 H2020 TeraFlow (https://www.teraflow-h2020.eu/)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

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()
