import logging, socket
from common.Constants import DEFAULT_CONTEXT_UUID
from common.Settings import get_setting
from interdomain.Config import GRPC_SERVICE_PORT
from interdomain.client.InterdomainClient import InterdomainClient
from interdomain.proto.context_pb2 import TeraFlowController

LOGGER = logging.getLogger(__name__)

class RemoteDomainClients:
    def __init__(self) -> None:
        self.peer_domain = {}

    def add_peer(
            self, domain_name : str, address : str, port : int, context_uuid : str = DEFAULT_CONTEXT_UUID
        ) -> None:
        while True:
            try:
                remote_teraflow_ip = socket.gethostbyname(address)
                if len(remote_teraflow_ip) > 0: break
            except socket.gaierror as e:
                if str(e) == '[Errno -2] Name or service not known': continue

        interdomain_client = InterdomainClient(address, port)
        request = TeraFlowController()
        request.context_id.context_uuid.uuid = DEFAULT_CONTEXT_UUID # pylint: disable=no-member
        request.ip_address = get_setting('INTERDOMAINSERVICE_SERVICE_HOST', default='0.0.0.0')
        request.port = int(get_setting('INTERDOMAINSERVICE_SERVICE_PORT_GRPC', default=GRPC_SERVICE_PORT))

        reply = interdomain_client.Authenticate(request)
        if not reply.authenticated:
            msg = 'Authentication against {:s}:{:d} rejected'
            raise Exception(msg.format(str(remote_teraflow_ip), GRPC_SERVICE_PORT))

        self.peer_domain[domain_name] = interdomain_client

    def get_peer(self, domain_name : str) -> InterdomainClient:
        LOGGER.warning('peers: {:s}'.format(str(self.peer_domain)))
        return self.peer_domain.get(domain_name)

    def remove_peer(self, domain_name : str) -> None:
        return self.peer_domain.pop(domain_name, None)
