from concurrent import futures

import grpc

from monitoring.proto import monitoring_pb2_grpc
from monitoring.service.MonitoringServiceServicerImpl import MonitoringServiceServicerImpl
from monitoring.Config import GRPC_SERVICE_PORT, GRPC_MAX_WORKERS, GRPC_GRACE_PERIOD

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 monitoring.proto.monitoring_pb2_grpc import  add_MonitoringServiceServicer_to_server

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

BIND_ADDRESS = '0.0.0.0'

class MonitoringService:
    def __init__(self, address=BIND_ADDRESS, port=GRPC_SERVICE_PORT, max_workers=GRPC_MAX_WORKERS,
                 grace_period=GRPC_GRACE_PERIOD):
        self.address = address
        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.monitoring_servicer = MonitoringServiceServicerImpl()
        add_MonitoringServiceServicer_to_server(self.monitoring_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')

