#!/usr/bin/python

import os
from concurrent import futures
import grpc

import numpy
import time

import monitoring_pb2
import monitoring_pb2_grpc

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


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

from prometheus_client import start_http_server, Summary

import threading

from prometheus_client import start_http_server, Summary
from prometheus_client import Counter, Gauge

MONITORING_GETINSTANTKPI_REQUEST_TIME = Summary('monitoring_getinstantkpi_processing_seconds', 'Time spent processing monitoring instant kpi request')
MONITORING_INCLUDEKPI_COUNTER = Counter('monitoring_includekpi_counter', 'Monitoring include kpi request counter')


class monitoringService(monitoring_pb2_grpc.MonitoringServiceServicer):
    def __init__(self):
        logger.info("init monitoringService")


    def IncludeKpi(self, request, context):
        #KPI, returns empty
        logger.info("IncludeKpi")
        MONITORING_INCLUDEKPI_COUNTER.inc()
        return 


    def MonitorKpi ( self, request, context):
        #KpiDevice returns (google.protobuf.Empty) {}
        logger.info("IncludeKpi")
        return 

    def GetStream_kpi ( self, request, context):
        #KpiId ) returns (stream Kpi) {}
        logger.info("IncludeKpi")
        return 

    @MONITORING_GETINSTANTKPI_REQUEST_TIME.time()
    def GetInstantKpi ( self, request, context):
        #KpiId ) returns ( Kpi) {}
        logger.info("IncludeKpi")
        return   


if __name__ == "__main__":
    logger.info("initializing monitoringService")

    port = os.environ.get('PORT', "7070")

    # create gRPC server
    serverGRPC = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) # ,interceptors=(tracer_interceptor,))

    # add class to gRPC server
    service = monitoring_pb2_grpc.MonitoringService()
    monitoring_pb2_grpc.add_MonitoringServiceServicer_to_server(service, serverGRPC)

    health_servicer = health.HealthServicer(experimental_non_blocking=True,experimental_thread_pool=futures.ThreadPoolExecutor(max_workers=1))
    health_pb2_grpc.add_HealthServicer_to_server(health_servicer, serverGRPC)

    # start server
    logger.info("listening on port: " + port)
    serverGRPC.add_insecure_port('[::]:'+port)
    serverGRPC.start()
    health_servicer.set("", health_pb2.HealthCheckResponse.SERVING)

    # keep alive
    try:
         while True:
            time.sleep(0.1)
    except KeyboardInterrupt:
            serverGRPC.stop(0)

