import grpc, logging
from common.Constants import ServiceNameEnum
from common.Settings import get_service_host, get_service_port_grpc
from common.proto.resource_manager_pb2 import L2Request, L2Response, L3Request, L3Response
from common.proto.resource_manager_pb2_grpc import ResourceManagerStub
from common.tools.client.RetryDecorator import retry, delay_exponential
from common.tools.grpc.Tools import grpc_message_to_json_string

LOGGER = logging.getLogger(__name__)
MAX_RETRIES = 15
DELAY_FUNCTION = delay_exponential(initial=0.01, increment=2.0, maximum=5.0)
RETRY_DECORATOR = retry(max_retries=MAX_RETRIES, delay_function=DELAY_FUNCTION, prepare_method_name='connect')


class ResourceManagerClient:
    def __init__(self, host=None, port=None):
        if not host:
            host = get_service_host(ServiceNameEnum.RESOURCE_MANAGER)
        if not port:
            port = get_service_port_grpc(ServiceNameEnum.RESOURCE_MANAGER)
        self.endpoint = f"{host}:{port}"
        LOGGER.info(f"Creating channel to {self.endpoint}...")
        self.channel = None
        self.stub = None
        self.connect()
        LOGGER.info("Channel created")

    def connect(self):
        self.channel = grpc.insecure_channel(self.endpoint)
        self.stub = ResourceManagerStub(self.channel)

    def close(self):
        if self.channel is not None:
            self.channel.close()
        self.channel = None
        self.stub = None

    @RETRY_DECORATOR
    def VerifyAndAssignL2(self, request: L2Request) -> L2Response:
        LOGGER.info(f"VerifyAndAssignL2 request: {grpc_message_to_json_string(request)}")
        response = self.stub.VerifyAndAssignL2(request)
        LOGGER.info(f"VerifyAndAssignL2 response: {grpc_message_to_json_string(response)}")
        return response

    @RETRY_DECORATOR
    def VerifyAndAssignL3(self, request: L3Request) -> L3Response:
        LOGGER.info(f"VerifyAndAssignL3 request: {grpc_message_to_json_string(request)}")
        response = self.stub.VerifyAndAssignL3(request)
        LOGGER.info(f"VerifyAndAssignL3 response: {grpc_message_to_json_string(response)}")
        return response