# 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
from grpc_health.v1.health import HealthServicer, OVERALL_HEALTH
from grpc_health.v1.health_pb2 import HealthCheckResponse
from grpc_health.v1.health_pb2_grpc import add_HealthServicer_to_server
from common.orm.backend.BackendEnum import BackendEnum
from common.orm.Database import Database
from common.orm.Factory import get_database_backend
from context.client.ContextClient import ContextClient
from device.Config import GRPC_SERVICE_PORT, GRPC_MAX_WORKERS, GRPC_GRACE_PERIOD
from device.proto.device_pb2_grpc import add_DeviceServiceServicer_to_server
from monitoring.client.monitoring_client import MonitoringClient
from .driver_api.DriverInstanceCache import DriverInstanceCache
from .DeviceServiceServicerImpl import DeviceServiceServicerImpl
from .MonitoringLoops import MonitoringLoops

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

class DeviceService:
    def __init__(
        self, context_client : ContextClient, monitoring_client : MonitoringClient,
        driver_instance_cache : DriverInstanceCache,
        address=BIND_ADDRESS, port=GRPC_SERVICE_PORT, max_workers=GRPC_MAX_WORKERS, grace_period=GRPC_GRACE_PERIOD):

        self.context_client = context_client
        self.monitoring_client = monitoring_client
        self.driver_instance_cache = driver_instance_cache
        self.address = address
        self.port = port
        self.endpoint = None
        self.max_workers = max_workers
        self.grace_period = grace_period
        self.device_servicer = None
        self.health_servicer = None
        self.pool = None
        self.server = None

        self.database = Database(get_database_backend(backend=BackendEnum.INMEMORY))
        self.monitoring_loops = MonitoringLoops(monitoring_client, self.database)

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

        self.monitoring_loops.start()

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

        self.device_servicer = DeviceServiceServicerImpl(
            self.context_client, self.database, self.driver_instance_cache, self.monitoring_loops)
        add_DeviceServiceServicer_to_server(self.device_servicer, self.server)

        self.health_servicer = HealthServicer(
            experimental_non_blocking=True, experimental_thread_pool=futures.ThreadPoolExecutor(max_workers=1))
        add_HealthServicer_to_server(self.health_servicer, self.server)

        port = self.server.add_insecure_port(self.endpoint)
        self.endpoint = '{:s}:{:s}'.format(str(self.address), str(port))
        LOGGER.info('Listening on {:s}...'.format(str(self.endpoint)))
        self.server.start()
        self.health_servicer.set(OVERALL_HEALTH, HealthCheckResponse.SERVING) # pylint: disable=maybe-no-member

        LOGGER.debug('Service started')

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