from concurrent import futures

import grpc

from interdomain.service.InterdomainServiceServicerImpl import InterdomainServiceServicerImpl
from interdomain.Config import GRPC_SLICE_PORT, GRPC_MAX_WORKERS, GRPC_GRACE_PERIOD
from interdomain.proto.interdomain_pb2_grpc import  add_InterdomainServiceServicer_to_server

from grpc_health.v1 import health
from grpc_health.v1 import health_pb2
from grpc_health.v1.health_pb2_grpc import add_HealthServicer_to_server

from common.logger import getJSONLogger
LOGGER = getJSONLogger('interdomainservice-server')
LOGGER.setLevel('DEBUG')

BIND_ADDRESS = '0.0.0.0'

class InterdomainService:
    def __init__(self, address=BIND_ADDRESS, slice_client=None, port=GRPC_INTERDOMAIN_PORT, max_workers=GRPC_MAX_WORKERS,
                 grace_period=GRPC_GRACE_PERIOD):
        self.address = address
        self.slice_client = slice_client
        self.port = port
        self.endpoint = None
        self.max_workers = max_workers
        self.grace_period = grace_period
        self.monitoring_servicer = None
        self.health_servicer = None
        self.pool = None
        self.server = None

    def start(self):
        # create gRPC server
        self.server = grpc.server(futures.ThreadPoolExecutor(max_workers=self.max_workers)) # ,interceptors=(tracer_interceptor,))

        # add monitoring servicer class to gRPC server
        self.interdomain_servicer = InterdomainServiceServicerImpl()
        add_InterdomainServiceServicer_to_server(self.interdomain_servicer, self.server)

        # add gRPC health checker servicer class to gRPC server
        self.health_servicer = health.HealthServicer(
            experimental_non_blocking=True, experimental_thread_pool=futures.ThreadPoolExecutor(max_workers=1))
        add_HealthServicer_to_server(self.health_servicer, self.server)

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

        LOGGER.debug('Service started')

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

