# 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 grpc, logging
from concurrent import futures

GRPC_MAX_WORKERS  = 10
GRPC_GRACE_PERIOD = 60

class MockService:
    def __init__(self, address, port, max_workers=GRPC_MAX_WORKERS, grace_period=GRPC_GRACE_PERIOD, cls_name=__name__):
        self.logger = logging.getLogger(cls_name)
        self.address = address
        self.port = port
        self.endpoint = None
        self.max_workers = max_workers
        self.grace_period = grace_period
        self.pool = None
        self.server = None

    def install_servicers(self):
        pass

    def start(self):
        self.endpoint = '{:s}:{:s}'.format(str(self.address), str(self.port))
        self.logger.info('Starting Service (tentative endpoint: {:s}, max_workers: {:s})...'.format(
            str(self.endpoint), str(self.max_workers)))

        self.pool = futures.ThreadPoolExecutor(max_workers=self.max_workers)
        self.server = grpc.server(self.pool) # , interceptors=(tracer_interceptor,))

        self.install_servicers()

        port = self.server.add_insecure_port(self.endpoint)
        self.endpoint = '{:s}:{:s}'.format(str(self.address), str(port))
        self.logger.info('Listening on {:s}...'.format(str(self.endpoint)))
        self.server.start()

        self.logger.debug('Service started')

    def stop(self):
        self.logger.debug('Stopping service (grace period {:s} seconds)...'.format(str(self.grace_period)))
        self.server.stop(self.grace_period)
        self.logger.debug('Service stopped')
