# Copyright 2022-2023 ETSI TeraFlowSDN - TFS OSG (https://tfs.etsi.org/)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import logging, socket
from common.Constants import DEFAULT_CONTEXT_NAME, ServiceNameEnum
from common.Settings import get_service_host, get_service_port_grpc
from common.proto.context_pb2 import TeraFlowController
from interdomain.client.InterdomainClient import InterdomainClient

LOGGER = logging.getLogger(__name__)

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

    def add_peer(
            self, domain_name : str, host : str, port : int, context_uuid : str = DEFAULT_CONTEXT_NAME
        ) -> None:
        while True:
            try:
                remote_teraflow_ip = socket.gethostbyname(host)
                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(host=host, port=port)
        request = TeraFlowController()
        request.context_id.context_uuid.uuid = DEFAULT_CONTEXT_NAME # pylint: disable=no-member
        request.ip_address = get_service_host(ServiceNameEnum.INTERDOMAIN)
        request.port = int(get_service_port_grpc(ServiceNameEnum.INTERDOMAIN))

        reply = interdomain_client.Authenticate(request)
        if not reply.authenticated:
            msg = 'Authentication against {:s}:{:d} rejected'
            raise Exception(msg.format(str(remote_teraflow_ip), 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)
